Skip to main content

schedr_api/
views.rs

1//! The JSON shapes of the REST API: what it returns and what it accepts.
2//!
3//! They are the API's own types, apart from the database's and the model's, so the API
4//! changes only on purpose (within `/api/v1`, additively). Times are UTC, RFC 3339; kinds and
5//! states are their model names (clients treat them as open: new values may appear).
6
7use std::collections::{BTreeMap, HashMap};
8
9use jiff::Timestamp;
10use schedr_config::masked::mask_text;
11use schedr_db::backfills::BackfillRecord;
12use schedr_db::commands::CommandRecord;
13use schedr_db::dags::StoredDag;
14use schedr_db::reads::{AttemptRecord, InstanceRecord, RunRecord};
15use schedr_db::runs::Held;
16use schedr_db::workers::WorkerRecord;
17use schedr_model::{DagId, DagLocation, RunState};
18use serde::{Deserialize, Serialize};
19use utoipa::{IntoParams, ToSchema};
20
21mod form;
22#[cfg(test)]
23mod tests;
24
25pub use form::{ParamFieldView, ParamKind};
26
27/// An error.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
29pub struct ErrorBody {
30    /// What went wrong.
31    pub error: String,
32}
33
34/// Where a DAG is defined.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
36pub struct LocationView {
37    /// The DAG root.
38    pub root: String,
39    /// The file, relative to the root.
40    pub path: String,
41}
42
43impl From<&DagLocation> for LocationView {
44    fn from(location: &DagLocation) -> Self {
45        Self {
46            root: location.root.clone(),
47            path: location.path.clone(),
48        }
49    }
50}
51
52/// A DAG's trigger's switch (decision 459).
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
54#[serde(rename_all = "snake_case")]
55pub enum TriggerState {
56    /// Switched off: it starts no runs; runs started by hand still run.
57    Paused,
58    /// Switched on.
59    Active,
60}
61
62impl TriggerState {
63    /// As `dags list` shows it, `manual` without a trigger.
64    #[must_use]
65    pub const fn shown(state: Option<Self>) -> &'static str {
66        match state {
67            Some(Self::Paused) => "paused",
68            Some(Self::Active) => "active",
69            None => "manual",
70        }
71    }
72}
73
74/// A DAG.
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
76pub struct DagView {
77    /// Its ID.
78    pub dag_id: String,
79    /// Its trigger's switch (decision 459): `paused` or `active`; `null` without a trigger (it
80    /// runs only when started by hand).
81    pub trigger_state: Option<TriggerState>,
82    /// Where its current version is defined (none for a DAG only ever seen in conflict).
83    pub location: Option<LocationView>,
84    /// Every place defining it, while it is in conflict (then it can't run).
85    pub conflict: Option<Vec<LocationView>>,
86    /// Its trigger as in DAG JSON.
87    #[schema(value_type = Option<Object>)]
88    pub trigger: Option<serde_json::Value>,
89    /// Its description.
90    pub description: Option<String>,
91    /// Its tags.
92    pub tags: Vec<String>,
93    /// Why it is held, while its file fails to import in its root's current code (decision
94    /// 72): the scheduler creates no runs of it and manual triggers are refused until it
95    /// imports again. Not set for a timeout or a runner that died (the file is parsed again).
96    pub held: Option<HeldView>,
97    /// The concurrency limits its current version sets, each with how many run now (decision
98    /// 96): only on one DAG's view (`GET /api/v1/dags/{dag_id}`), not in the list.
99    #[serde(default, skip_serializing_if = "Vec::is_empty")]
100    pub limits: Vec<LimitView>,
101    /// The run parameters its current version takes, as the UI's trigger form shows them
102    /// (decision 149): only on one DAG's view, not in the list; none when it takes none.
103    #[serde(default, skip_serializing_if = "Vec::is_empty")]
104    pub params: Vec<ParamFieldView>,
105    /// What is wrong with its current version that shows only when a run reaches it: a
106    /// connection a task declares that its root's current files don't define, or define twice
107    /// (decision 179). Only on one DAG's view, not in the list.
108    #[serde(default, skip_serializing_if = "Vec::is_empty")]
109    pub warnings: Vec<String>,
110}
111
112/// A concurrency limit and how many of what it limits run now: open attempts (assigned, not
113/// yet started, running, cleaning up), as the master counts them.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
115pub struct LimitView {
116    /// `max_active_tasks`, `max_active` or `max_active_per_run`.
117    pub limit: String,
118    /// The task it is set on; none for `max_active_tasks` (the DAG's).
119    pub task_id: Option<String>,
120    /// Its value.
121    pub value: u32,
122    /// How many run now: the DAG's tasks, the task's instances across runs, or, for
123    /// `max_active_per_run`, the most in any one run.
124    pub running: u32,
125}
126
127impl LimitView {
128    /// The limits `dag` sets, counted from `counts` (`(run, task, open attempts)` of its runs).
129    #[must_use]
130    pub fn of(
131        dag: &schedr_model::Dag,
132        counts: &[(String, schedr_model::TaskId, u32)],
133    ) -> Vec<Self> {
134        let mut limits = Vec::new();
135        if let Some(value) = dag.max_active_tasks {
136            limits.push(Self {
137                limit: "max_active_tasks".to_owned(),
138                task_id: None,
139                value,
140                running: counts.iter().map(|c| c.2).sum(),
141            });
142        }
143        for task in &dag.tasks {
144            let of_task = || counts.iter().filter(|c| c.1 == task.id).map(|c| c.2);
145            if let Some(value) = task.settings.max_active {
146                limits.push(Self {
147                    limit: "max_active".to_owned(),
148                    task_id: Some(task.id.to_string()),
149                    value,
150                    running: of_task().sum(),
151                });
152            }
153            if let Some(value) = task.settings.max_active_per_run {
154                limits.push(Self {
155                    limit: "max_active_per_run".to_owned(),
156                    task_id: Some(task.id.to_string()),
157                    value,
158                    running: of_task().max().unwrap_or(0),
159                });
160            }
161        }
162        limits
163    }
164}
165
166/// Why a DAG is held: its file's import error. The error is the **file's**, so every DAG of
167/// the file is held (decision 72.3).
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
169pub struct HeldView {
170    /// What happened and what to do, for people: that the file failed (not only this DAG),
171    /// why, and how to fix it.
172    pub reason: String,
173    /// The file, relative to its root.
174    pub path: String,
175    /// The error's exception class name, e.g. `ModuleNotFoundError`.
176    pub exception: String,
177    /// The error's message.
178    pub message: String,
179}
180
181impl DagView {
182    /// The view of `dag`, held if its file is among `held` ([`Held::by_file`] of the current
183    /// import errors).
184    #[must_use]
185    pub fn of(dag: &StoredDag, held: &HashMap<(String, String), Held>) -> Self {
186        let current = dag.current.as_ref().map(|c| &c.dag);
187        Self {
188            dag_id: dag.dag_id.to_string(),
189            trigger_state: dag.paused.map(|paused| {
190                if paused {
191                    TriggerState::Paused
192                } else {
193                    TriggerState::Active
194                }
195            }),
196            location: current.map(|d| (&d.location).into()),
197            conflict: dag
198                .conflict
199                .as_ref()
200                .map(|places| places.iter().map(Into::into).collect()),
201            trigger: current.and_then(|d| serde_json::to_value(&d.trigger).ok()),
202            description: current.and_then(|d| d.description.clone()),
203            tags: current.map(|d| d.tags.clone()).unwrap_or_default(),
204            held: current.and_then(|d| Held::of(d, held)).map(|h| HeldView {
205                reason: h.reason(dag.dag_id.as_str()),
206                path: h.path,
207                exception: h.exception,
208                message: mask_text(&h.message),
209            }),
210            limits: Vec::new(),
211            params: Vec::new(),
212            warnings: Vec::new(),
213        }
214    }
215}
216
217/// The DAGs.
218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
219pub struct DagList {
220    /// Every DAG not removed, in ID order.
221    pub dags: Vec<DagView>,
222}
223
224/// A run.
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
226pub struct RunView {
227    /// Its ID (a UUIDv7).
228    pub run_id: String,
229    /// The DAG.
230    pub dag_id: String,
231    /// `scheduled`, `manual`, `backfill`, `chained` or `event`.
232    pub kind: String,
233    /// `queued`, `running`, `success`, `failed` or `cancelled`.
234    pub state: String,
235    /// The moment it is for.
236    pub planned_for: Timestamp,
237    /// The start of its window, `(since, planned_for]`.
238    pub since: Timestamp,
239    /// When it was created.
240    pub triggered_at: Timestamp,
241    /// `scheduler`, a user name, the parent run, or `trigger`.
242    pub triggered_by: String,
243    /// When it started running.
244    pub started_at: Option<Timestamp>,
245    /// When it finished.
246    pub ended_at: Option<Timestamp>,
247    /// A `success` that learnt of a failure after its end, shown yellow (decision 309): why,
248    /// `late_cleanup_failed` for now.
249    pub late_failure: Option<String>,
250    /// The run whose `TriggerDagOperator` started it, for a `chained` run, or whose success
251    /// started it, for a run of a `RunOf` trigger.
252    #[serde(default)]
253    pub parent_run_id: Option<String>,
254    /// Its backfill and its place in it, for a `backfill` run (`backfill 3/31`).
255    #[serde(default)]
256    pub backfill: Option<RunBackfillView>,
257}
258
259/// A backfill run's backfill and its place among the backfill's runs, oldest first.
260#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
261pub struct RunBackfillView {
262    /// The backfill's ID.
263    pub backfill_id: String,
264    /// Its place, from 1.
265    pub index: u32,
266    /// How many runs the backfill has.
267    pub total: u32,
268}
269
270impl RunView {
271    /// Its kind as people read it: a backfill's run with its place among the backfill's runs,
272    /// oldest first (`backfill 3/31`, decision 403).
273    #[must_use]
274    pub fn kind_label(&self) -> String {
275        match &self.backfill {
276            Some(place) => format!("{} {}/{}", self.kind, place.index, place.total),
277            None => self.kind.clone(),
278        }
279    }
280}
281
282impl From<&RunRecord> for RunView {
283    fn from(run: &RunRecord) -> Self {
284        Self {
285            run_id: run.id.clone(),
286            dag_id: run.dag_id.to_string(),
287            kind: run.kind.to_string(),
288            state: run.state.to_string(),
289            planned_for: run.planned_for,
290            since: run.since,
291            triggered_at: run.triggered_at,
292            triggered_by: run.triggered_by.clone(),
293            started_at: run.started_at,
294            ended_at: run.ended_at,
295            late_failure: run.late_failure.clone(),
296            parent_run_id: run.parent_run_id.clone(),
297            backfill: run.backfill.as_ref().map(|b| RunBackfillView {
298                backfill_id: b.id.clone(),
299                index: b.index,
300                total: b.total,
301            }),
302        }
303    }
304}
305
306/// Runs.
307#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
308pub struct RunList {
309    /// Newest first: a DAG's by `planned_for`; the list over every DAG by `triggered_at`, then
310    /// run ID.
311    pub runs: Vec<RunView>,
312}
313
314/// A task of a run.
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
316pub struct TaskView {
317    /// The task's ID.
318    pub task_id: String,
319    /// Which instance of a mapped task, from 0; -1 for an unmapped task, and for a mapped
320    /// task as a whole (decision 80).
321    #[serde(default = "unmapped")]
322    pub map_index: i32,
323    /// A mapped task as a whole: how many instances it has (0 before it expands, or for an
324    /// empty list); `null` for an unmapped task and for an instance.
325    #[serde(default)]
326    pub instances: Option<usize>,
327    /// Its state (`scheduled`, `queued`, `running`, `success`, ...).
328    pub state: String,
329    /// Its outcome, on success.
330    pub outcome: Option<String>,
331    /// Attempts made.
332    pub try_number: u32,
333    /// Why it waits or can't be scheduled, or why a mapped task failed without an attempt
334    /// (too many instances, a mapped value that isn't a list).
335    pub reason: Option<String>,
336    /// How its cleanups ended (`ok`, `failed`, `worker_lost`, `not_needed`): the last, unless
337    /// one failed; none for a task without a cleanup, or before its first one ends.
338    #[serde(default)]
339    pub cleanup: Option<String>,
340    /// When it last changed.
341    pub updated_at: Timestamp,
342}
343
344/// The `map_index` of a task that isn't mapped (read from an answer that leaves it out).
345const fn unmapped() -> i32 {
346    -1
347}
348
349impl TaskView {
350    /// The view of `instance`; `instances` for a mapped task as a whole.
351    #[must_use]
352    pub fn of(instance: &InstanceRecord, instances: Option<usize>) -> Self {
353        Self {
354            task_id: instance.task_id.to_string(),
355            map_index: instance.map_index,
356            instances,
357            state: instance.state.to_string(),
358            outcome: instance.outcome.clone(),
359            try_number: instance.try_number,
360            reason: instance
361                .reason
362                .clone()
363                .or_else(|| instance.queued_reason.clone()),
364            cleanup: instance.cleanup_result.map(|r| r.to_string()),
365            updated_at: instance.updated_at,
366        }
367    }
368}
369
370/// Which instance of a mapped task (decisions 81, 82).
371#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, IntoParams)]
372#[serde(deny_unknown_fields)]
373#[into_params(parameter_in = Query)]
374pub struct InstanceQuery {
375    /// The instance, from 0 (a mapped task only). For an output, none gives the mapped task's
376    /// whole list; for a cancel, the whole task; attempts, logs and a retry need it.
377    #[serde(default)]
378    pub map_index: Option<i32>,
379}
380
381/// A run with its tasks.
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
383pub struct RunDetail {
384    /// The run.
385    pub run: RunView,
386    /// Its tasks, in task ID order.
387    pub tasks: Vec<TaskView>,
388    /// The code hashes its attempts ran with, in the order first used. More than one: its
389    /// tasks ran on different code (it changed during the run).
390    pub code_hashes: Vec<String>,
391    /// Its parameters as JSON, masked like a task's output (decision 134); `{}` for a DAG
392    /// that takes none.
393    #[serde(default)]
394    #[schema(value_type = Object)]
395    pub params: serde_json::Value,
396    /// Its resources, in the DAG's order (decision 275: each one's state from its two tasks).
397    #[serde(default)]
398    pub resources: Vec<ResourceView>,
399}
400
401/// A run's resources.
402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
403pub struct ResourceList {
404    /// In the DAG's order.
405    pub resources: Vec<ResourceView>,
406}
407
408/// A wait step switched off for getting its host killed too many times in a row (decision 338).
409#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
410pub struct SensorView {
411    /// Its DAG.
412    pub dag_id: String,
413    /// The wait step.
414    pub sensor: String,
415    /// Its host kills in a row.
416    pub strikes: u32,
417    /// When it was switched off (RFC 3339).
418    pub switched_off_at: String,
419}
420
421/// The wait steps switched off.
422#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
423pub struct SensorList {
424    /// By DAG and task.
425    pub sensors: Vec<SensorView>,
426}
427
428/// A resource of a run: its setup, its cleanup and its users.
429#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
430pub struct ResourceView {
431    /// Its name: its setup's task ID.
432    pub setup: String,
433    /// Its cleanup's task ID.
434    pub cleanup: String,
435    /// The tasks that use it, in the DAG's order.
436    pub users: Vec<String>,
437    /// Whether what follows its group waits for its cleanup.
438    pub blocking: bool,
439    /// `setting_up`, `waiting_for_users`, `cleaning_up`, `cleaned`, `cleanup_failed`,
440    /// `cleanup_cancelled` (cancelled by hand: what the setup made may be left) or `not_needed`.
441    pub state: String,
442}
443
444/// An attempt of a task.
445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
446pub struct AttemptView {
447    /// Its ID.
448    pub attempt_id: String,
449    /// Its try number.
450    pub try_number: u32,
451    /// The worker it ran on.
452    pub worker_id: Option<String>,
453    /// How it ended (`success`, `failed`, `timed_out`, ...); none while it runs.
454    pub status: Option<String>,
455    /// The process's exit code.
456    pub exit_code: Option<i32>,
457    /// The error kind schedr recognised.
458    pub error_kind: Option<String>,
459    /// The structured error summary (exception, message, traceback).
460    #[schema(value_type = Option<Object>)]
461    pub error_summary: Option<serde_json::Value>,
462    /// When it was assigned.
463    pub assigned_at: Timestamp,
464    /// When the worker started it.
465    pub started_at: Option<Timestamp>,
466    /// When it ended.
467    pub ended_at: Option<Timestamp>,
468    /// How long it ran, measured by the worker (the timestamps come from the master's wall
469    /// clock, so don't subtract them); none while it runs or for attempts ended by the master.
470    pub duration_ms: Option<u64>,
471    /// The peak memory of its processes, sampled by the worker (about once a second); none
472    /// when it wasn't measured.
473    pub peak_memory_bytes: Option<u64>,
474    /// How the worker started it: `spawn` (a new process: an interpreter for a Python task,
475    /// the command for a command task) or `fork` (from the fork server); none until the
476    /// worker reported its start.
477    pub start_method: Option<String>,
478    /// What its process used, with the children it reaped (its parent's view at its exit);
479    /// none while it runs, when the worker couldn't read it, or for attempts ended by the
480    /// master.
481    pub usage: Option<UsageView>,
482    /// Whether its process dumped core (ended by a signal).
483    pub core_dumped: bool,
484    /// Its cleanup; none for a task without one.
485    #[serde(default)]
486    pub cleanup: Option<CleanupView>,
487    /// The run a `TriggerDagOperator`'s attempt started (no worker runs it).
488    #[serde(default)]
489    pub chained_run_id: Option<String>,
490}
491
492/// An attempt's cleanup.
493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
494pub struct CleanupView {
495    /// How it ended (`ok`, `failed`, `worker_lost`, `not_needed`); none until it has.
496    pub result: Option<String>,
497    /// The tries it made.
498    pub tries: Option<u32>,
499    /// How long its tries ran, measured by the worker.
500    pub duration_ms: Option<u64>,
501    /// The error kind of its last failed try.
502    pub error_kind: Option<String>,
503    /// The structured error summary of its last failed try.
504    #[schema(value_type = Option<Object>)]
505    pub error_summary: Option<serde_json::Value>,
506    /// How many times it moved to another worker (`cleanup_anywhere`).
507    pub moves: u32,
508    /// The handles the attempt registered (`{"handle_type": ..., "value": ...}`), masked, in
509    /// order.
510    #[schema(value_type = Vec<Object>)]
511    pub handles: Vec<serde_json::Value>,
512}
513
514/// What an attempt's process used.
515#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
516pub struct UsageView {
517    /// CPU time in user mode, in microseconds.
518    pub user_cpu_micros: u64,
519    /// CPU time in the kernel, in microseconds.
520    pub system_cpu_micros: u64,
521    /// The peak resident set size, in bytes; for a forked process it includes the pages it
522    /// shares with the fork server (`peak_memory_bytes`, the watchdog's PSS, doesn't); none
523    /// for a spawned process (its memory is gone when the worker reads it).
524    pub peak_rss_bytes: Option<u64>,
525    /// Page faults that needed I/O.
526    pub major_faults: u64,
527    /// Times it gave up the CPU (waiting for I/O or a lock), with its threads and reaped
528    /// children; none for a spawned process (only its leader thread's could be read).
529    pub voluntary_context_switches: Option<u64>,
530    /// Times it was preempted; none as for `voluntary_context_switches`.
531    pub involuntary_context_switches: Option<u64>,
532}
533
534impl From<&AttemptRecord> for AttemptView {
535    fn from(attempt: &AttemptRecord) -> Self {
536        Self {
537            attempt_id: attempt.id.clone(),
538            try_number: attempt.try_number,
539            worker_id: attempt.worker_id.clone(),
540            status: attempt.status.map(|s| s.to_string()),
541            exit_code: attempt.exit_code,
542            error_kind: attempt.error_kind.clone(),
543            error_summary: attempt
544                .error_summary
545                .as_deref()
546                .and_then(|s| serde_json::from_str(s).ok())
547                .map(|mut summary| {
548                    schedr_config::masked::mask(&mut summary);
549                    summary
550                }),
551            assigned_at: attempt.assigned_at,
552            started_at: attempt.started_at,
553            ended_at: attempt.ended_at,
554            duration_ms: attempt.duration_ms,
555            peak_memory_bytes: attempt.peak_memory_bytes,
556            start_method: attempt.start_method.clone(),
557            usage: attempt.usage.map(|u| UsageView {
558                user_cpu_micros: u.user_cpu_micros,
559                system_cpu_micros: u.system_cpu_micros,
560                peak_rss_bytes: u.peak_rss_bytes,
561                major_faults: u.major_faults,
562                voluntary_context_switches: u.voluntary_context_switches,
563                involuntary_context_switches: u.involuntary_context_switches,
564            }),
565            core_dumped: attempt.core_dumped,
566            cleanup: (!attempt.cleanup.is_empty()).then(|| CleanupView {
567                result: attempt.cleanup.result.map(|r| r.to_string()),
568                tries: attempt.cleanup.tries,
569                duration_ms: attempt.cleanup.duration_ms,
570                error_kind: attempt.cleanup.error_kind.clone(),
571                error_summary: attempt
572                    .cleanup
573                    .error_summary
574                    .as_deref()
575                    .and_then(|s| serde_json::from_str(s).ok())
576                    .map(|mut summary| {
577                        schedr_config::masked::mask(&mut summary);
578                        summary
579                    }),
580                moves: attempt.cleanup.moves,
581                handles: attempt
582                    .cleanup
583                    .handles
584                    .iter()
585                    .map(|h| shown_handle(h))
586                    .collect(),
587            }),
588            chained_run_id: attempt.chained_run_id.clone(),
589        }
590    }
591}
592
593/// A stored handle as shown: masked as a task's data, by its field names and texts (the agent
594/// masked only the secrets the attempt read); one that doesn't parse is shown as `{"unreadable": <text>}`,
595/// masked, rather than left out.
596fn shown_handle(stored: &str) -> serde_json::Value {
597    let mut value = serde_json::from_str(stored)
598        .unwrap_or_else(|_| serde_json::json!({ "unreadable": mask_text(stored) }));
599    schedr_config::masked::mask_data(&mut value);
600    value
601}
602
603/// A task's attempts.
604#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
605pub struct AttemptList {
606    /// Oldest first.
607    pub attempts: Vec<AttemptView>,
608}
609
610/// A command: an action the master applies, then marks `applied` or `rejected`.
611#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
612pub struct CommandView {
613    /// Its ID; poll `GET /api/v1/commands/{command_id}` for the decision.
614    pub command_id: String,
615    /// `trigger_run`, `cancel_run`, `pause_dag` or `unpause_dag`.
616    pub kind: String,
617    /// `pending`, `applied` or `rejected`.
618    pub status: String,
619    /// Why it was rejected.
620    pub reason: Option<String>,
621    /// What it produced when applied, e.g. `{"run_id": ...}` for a trigger.
622    #[schema(value_type = Option<Object>)]
623    pub result: Option<serde_json::Value>,
624    /// Who asked for it.
625    pub requested_by: String,
626    /// When.
627    pub requested_at: Timestamp,
628    /// When the master decided it.
629    pub decided_at: Option<Timestamp>,
630}
631
632impl From<&CommandRecord> for CommandView {
633    fn from(command: &CommandRecord) -> Self {
634        Self {
635            command_id: command.id.clone(),
636            kind: command.kind.clone(),
637            status: serde_json::to_value(command.status)
638                .ok()
639                .and_then(|v| v.as_str().map(str::to_owned))
640                .unwrap_or_default(),
641            // A reason may quote a value given (a run's parameter, decision 134).
642            reason: command
643                .reason
644                .as_deref()
645                .map(schedr_config::masked::mask_text),
646            result: command.result.clone(),
647            requested_by: command.requested_by.clone(),
648            requested_at: command.requested_at,
649            decided_at: command.decided_at,
650        }
651    }
652}
653
654/// A manual run to start.
655#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
656#[serde(deny_unknown_fields)]
657pub struct TriggerRequest {
658    /// The moment the run is for (`--for`); now if not given. Must not be in the future.
659    #[serde(default)]
660    pub planned_for: Option<Timestamp>,
661    /// Values for the run's parameters, as JSON (`{"region": "us"}`), over the DAG's
662    /// defaults; checked by the master against the DAG's schema (decision 133).
663    #[serde(default, skip_serializing_if = "Option::is_none")]
664    #[schema(value_type = Option<Object>)]
665    pub params: Option<serde_json::Map<String, serde_json::Value>>,
666    /// For a DAG a trigger starts: the key of an event it found, to run again.
667    #[serde(default, skip_serializing_if = "Option::is_none")]
668    pub event: Option<String>,
669    /// Or an event given here: its key. It is never stored as an event.
670    #[serde(default, skip_serializing_if = "Option::is_none")]
671    pub event_key: Option<String>,
672    /// And its data, as JSON of any kind.
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub event_data: Option<serde_json::Value>,
675    /// And when it happened; the run's moment otherwise.
676    #[serde(default, skip_serializing_if = "Option::is_none")]
677    pub event_at: Option<Timestamp>,
678}
679
680/// A backfill to create (`schedr runs backfill`, decisions 363, 364, 400-404): a run per fire
681/// time of `[from, to]` with no successful, queued or running run, oldest first.
682#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
683#[serde(deny_unknown_fields)]
684pub struct BackfillRequest {
685    /// The range's first moment (inclusive).
686    pub from: Timestamp,
687    /// Its last moment (inclusive); now if not given, and a later one ends at now.
688    #[serde(default, skip_serializing_if = "Option::is_none")]
689    pub to: Option<Timestamp>,
690    /// A run for every fire time of the range, not only the missing ones (`--all`).
691    #[serde(default)]
692    pub all: bool,
693    /// Values for every run's parameters, as JSON, over the DAG's defaults; checked once.
694    #[serde(default, skip_serializing_if = "Option::is_none")]
695    #[schema(value_type = Option<Object>)]
696    pub params: Option<serde_json::Map<String, serde_json::Value>>,
697    /// Count only: the command's result says what would be created, and nothing is.
698    #[serde(default)]
699    pub dry_run: bool,
700}
701
702/// A backfill's runs by state.
703#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
704pub struct BackfillRunCounts {
705    /// Waiting for `max_active_runs`, behind the other kinds of runs.
706    pub queued: u32,
707    /// Running.
708    pub running: u32,
709    /// Succeeded.
710    pub success: u32,
711    /// Failed.
712    pub failed: u32,
713    /// Cancelled.
714    pub cancelled: u32,
715}
716
717/// A backfill (decision 403).
718#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
719pub struct BackfillView {
720    /// Its ID (the command's that created it).
721    pub backfill_id: String,
722    /// Its DAG.
723    pub dag_id: String,
724    /// The range's first moment.
725    pub from: Timestamp,
726    /// Its last moment (now, when it was asked for one later).
727    pub to: Timestamp,
728    /// Whether every fire time got a run (`--all`).
729    pub all: bool,
730    /// Who asked for it.
731    pub requested_by: String,
732    /// When.
733    pub created_at: Timestamp,
734    /// The fire times of its range.
735    pub fire_times: u32,
736    /// How many of them got a run; the others were skipped.
737    pub created_runs: u32,
738    /// Its runs by state.
739    pub runs: BackfillRunCounts,
740    /// Whether some of its runs are queued or running: what cancelling it would cancel.
741    pub unfinished: bool,
742}
743
744impl From<&BackfillRecord> for BackfillView {
745    fn from(backfill: &BackfillRecord) -> Self {
746        let mut runs = BackfillRunCounts::default();
747        for (state, count) in &backfill.runs {
748            let slot = match state {
749                RunState::Queued => &mut runs.queued,
750                RunState::Running => &mut runs.running,
751                RunState::Success => &mut runs.success,
752                RunState::Failed => &mut runs.failed,
753                RunState::Cancelled => &mut runs.cancelled,
754            };
755            *slot += count;
756        }
757        Self {
758            backfill_id: backfill.id.clone(),
759            dag_id: backfill.dag_id.to_string(),
760            from: backfill.range_from,
761            to: backfill.range_to,
762            all: backfill.all_fire_times,
763            requested_by: backfill.requested_by.clone(),
764            created_at: backfill.created_at,
765            fire_times: backfill.fire_times,
766            created_runs: backfill.created_runs,
767            runs,
768            unfinished: backfill.unfinished(),
769        }
770    }
771}
772
773/// A DAG's backfills, newest first.
774#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
775pub struct BackfillList {
776    /// The backfills.
777    pub backfills: Vec<BackfillView>,
778}
779
780/// A DAG's trigger.
781#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
782pub struct TriggerView {
783    /// Its DAG.
784    pub dag_id: String,
785    /// Its function.
786    pub trigger: String,
787    /// `running`, `waiting` (for a free watcher slot or to start again), `stopped` (see
788    /// `stopped_why`), `switched_off` or `paused` (its DAG's, or outside its `start` and `end`).
789    pub state: String,
790    /// The worker running it.
791    pub worker: Option<String>,
792    /// The last key acted on: what it starts from.
793    pub bookmark: Option<String>,
794    /// Why it isn't running although its DAG wants it: `back_pressure` or `returned`.
795    pub stopped_why: Option<String>,
796    /// Its errors in a row.
797    pub failures: u32,
798    /// Its last error.
799    pub last_error: Option<String>,
800    /// Not started again before this moment.
801    pub not_before: Option<Timestamp>,
802    /// When this run of it started.
803    pub started_at: Option<Timestamp>,
804    /// When it last found something.
805    pub last_event_at: Option<Timestamp>,
806    /// When a poke's call last ended.
807    pub last_poked_at: Option<Timestamp>,
808    /// When it was last started again for finding nothing for its `restart_if_idle`.
809    pub last_restart_at: Option<Timestamp>,
810    /// A running poke trigger none of whose calls has ended for over three times its `every`
811    /// plus a heartbeat: its worker may hang; `schedr triggers restart` starts it again.
812    #[serde(default)]
813    pub stuck: bool,
814    /// `@trigger(wait_for=...)` (decision 353): the run of the other DAG it is called for and
815    /// hasn't ended well with yet; `schedr triggers skip` passes it.
816    #[serde(default, skip_serializing_if = "Option::is_none")]
817    pub called_for: Option<String>,
818}
819
820/// The triggers.
821#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
822pub struct TriggerList {
823    /// By DAG.
824    pub triggers: Vec<TriggerView>,
825}
826
827/// An event a trigger found.
828#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
829pub struct EventView {
830    /// Its key.
831    pub key: String,
832    /// Its data, JSON of any kind.
833    pub data: serde_json::Value,
834    /// When it happened, if it said.
835    pub at: Option<Timestamp>,
836    /// When the master got it.
837    pub received_at: Timestamp,
838}
839
840/// An event to post (`POST /api/v1/events`, decision 354).
841#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
842#[serde(deny_unknown_fields)]
843pub struct PostEventRequest {
844    /// Its name, written as a DAG ID is.
845    pub name: String,
846    /// Its key: a trigger starts one run per key, a waiting step matches its own key.
847    pub key: String,
848    /// Its data, JSON of any kind; `null` if not given.
849    #[serde(default)]
850    pub data: serde_json::Value,
851    /// When it happened; now if not given. A run it starts is planned for it.
852    #[serde(default)]
853    pub at: Option<Timestamp>,
854}
855
856/// An event posted through the API.
857#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
858pub struct NamedEventView {
859    /// Its ID.
860    pub id: String,
861    /// Its name.
862    pub name: String,
863    /// Its key.
864    pub key: String,
865    /// Its data, masked as an output is.
866    pub data: serde_json::Value,
867    /// When it happened.
868    pub at: Timestamp,
869    /// When it was posted.
870    pub posted_at: Timestamp,
871    /// Who posted it.
872    pub posted_by: String,
873}
874
875/// Posted events.
876#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
877pub struct NamedEventList {
878    /// Newest posted first.
879    pub events: Vec<NamedEventView>,
880}
881
882/// A trigger's events.
883#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
884pub struct EventList {
885    /// Newest received first.
886    pub events: Vec<EventView>,
887}
888
889/// Connections to check on a worker (`schedr connections check`).
890#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
891#[serde(deny_unknown_fields)]
892pub struct CheckConnectionsRequest {
893    /// The root; every root with connections if not given.
894    #[serde(default, skip_serializing_if = "Option::is_none")]
895    pub root: Option<String>,
896    /// One connection; all of the root's if not given.
897    #[serde(default, skip_serializing_if = "Option::is_none")]
898    pub name: Option<String>,
899    /// The worker to run it on; one the master picks if not given.
900    #[serde(default, skip_serializing_if = "Option::is_none")]
901    pub worker: Option<String>,
902}
903
904/// A connection to test on a worker (`schedr connections test`).
905#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
906#[serde(deny_unknown_fields)]
907pub struct TestConnectionRequest {
908    /// Its root; the one root defining it if not given.
909    #[serde(default, skip_serializing_if = "Option::is_none")]
910    pub root: Option<String>,
911    /// The worker to run it on; one the master picks if not given.
912    #[serde(default, skip_serializing_if = "Option::is_none")]
913    pub worker: Option<String>,
914    /// How long it may take, in milliseconds: `[webserver] connection_test_timeout` if not given.
915    #[serde(default, skip_serializing_if = "Option::is_none")]
916    pub timeout_ms: Option<u64>,
917}
918
919/// Pausing a DAG.
920#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
921#[serde(deny_unknown_fields)]
922pub struct PauseRequest {
923    /// Also cancel its queued and running runs.
924    #[serde(default)]
925    pub cancel_runs: bool,
926}
927
928/// Which runs to list.
929#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, IntoParams)]
930#[serde(deny_unknown_fields)]
931#[into_params(parameter_in = Query)]
932pub struct RunsQuery {
933    /// Only the runs for this moment (`--for`).
934    #[serde(default, rename = "for")]
935    #[param(rename = "for", value_type = Option<String>, format = DateTime)]
936    pub planned_for: Option<Timestamp>,
937    /// At most this many (default 50, at most 500).
938    #[serde(default)]
939    pub limit: Option<u32>,
940}
941
942/// Which runs to list, over every DAG.
943#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, IntoParams)]
944#[serde(deny_unknown_fields)]
945#[into_params(parameter_in = Query)]
946pub struct AllRunsQuery {
947    /// Only this DAG's runs.
948    #[serde(default)]
949    #[param(value_type = Option<String>)]
950    pub dag: Option<DagId>,
951    /// Only the runs of DAGs whose ID holds this, in any case (`sync` matches `sync_orders`
952    /// and `Daily_Sync`).
953    #[serde(default)]
954    pub dag_contains: Option<String>,
955    /// Only runs in this state: `queued`, `running`, `success`, `failed` or `cancelled`.
956    #[serde(default)]
957    #[param(value_type = Option<String>)]
958    pub state: Option<RunState>,
959    /// Only runs triggered before this moment: the last listed run's `triggered_at`, for the
960    /// next page (with `before_run`).
961    #[serde(default)]
962    #[param(value_type = Option<String>, format = DateTime)]
963    pub before: Option<Timestamp>,
964    /// With `before`: the last listed run's ID, so runs triggered at that same moment (a
965    /// scheduler round triggers its runs together) are listed after it, by ID, not skipped.
966    #[serde(default)]
967    pub before_run: Option<String>,
968    /// At most this many (default 50, at most 500).
969    #[serde(default)]
970    pub limit: Option<u32>,
971}
972
973/// A task's stored output in a run.
974#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
975pub struct OutputView {
976    /// The outcome the task finished with.
977    pub outcome: String,
978    /// The value it returned, masked (decision 131: its texts' secrets, and a field whose
979    /// name has a word naming a secret); downstream tasks get it as stored.
980    pub value: serde_json::Value,
981}
982
983/// The commands about a run.
984#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
985pub struct CommandList {
986    /// Oldest first.
987    pub commands: Vec<CommandView>,
988}
989
990/// Which part of a log to read.
991#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, IntoParams)]
992#[serde(deny_unknown_fields)]
993#[into_params(parameter_in = Query)]
994pub struct LogQuery {
995    /// The first byte wanted (0 by default): the `next` of the previous part, to follow a log.
996    #[serde(default)]
997    pub from: Option<u64>,
998    /// At most this many bytes (1 MiB by default; between 4 bytes, one character, and that).
999    #[serde(default)]
1000    pub limit: Option<u64>,
1001    /// The instance of a mapped task, from 0 (required for one).
1002    #[serde(default)]
1003    pub map_index: Option<i32>,
1004}
1005
1006/// A part of an attempt's log, read from the worker that ran it.
1007#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1008pub struct LogChunk {
1009    /// The attempt.
1010    pub attempt_id: String,
1011    /// Its try number.
1012    pub try_number: u32,
1013    /// The worker it ran on (and that answered).
1014    pub worker_id: String,
1015    /// The first byte of `content`: the one asked for, or past it, at the start of the next
1016    /// line, when that one is inside a line.
1017    pub from: u64,
1018    /// Where the next part starts: the byte after `content`, or past it, after the part of
1019    /// a line longer than a part that isn't shown.
1020    pub next: u64,
1021    /// The log's size when it was read.
1022    pub size: u64,
1023    /// Whether the attempt still runs (its log may grow).
1024    pub running: bool,
1025    /// The log's text, whole lines only (a running attempt's last line once it ends), with
1026    /// its secrets masked: a password in an address, a value after a name like `password=`
1027    /// (invalid UTF-8 replaced by `U+FFFD`). A line longer than the part asked for is shown
1028    /// to its last whitespace in it, then `… (the rest of this line is not shown: it is over
1029    /// N bytes)`, its rest passed over.
1030    pub content: String,
1031}
1032
1033/// A worker in the registry (kept after it is gone, so its logs can be found).
1034#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1035pub struct WorkerView {
1036    /// Its ID.
1037    pub worker_id: String,
1038    /// `active`, `draining`, `disconnected`, `offline` or `lost`.
1039    pub state: String,
1040    /// The incarnation of its agent process it last registered with.
1041    pub incarnation_id: String,
1042    /// The queues it serves.
1043    pub queues: Vec<String>,
1044    /// Its task slots.
1045    pub slots: u32,
1046    /// Its attempts still running.
1047    pub running: u32,
1048    /// Its schedr version.
1049    pub schedr_version: String,
1050    /// Its protocol version (`major.minor`).
1051    pub protocol_version: String,
1052    /// Where its log endpoint listens (where a gone worker's logs were served).
1053    pub log_endpoint: String,
1054    /// When it last registered.
1055    pub registered_at: Timestamp,
1056    /// The last sign of life the master recorded (at most once per heartbeat interval).
1057    pub last_heartbeat_at: Timestamp,
1058    /// When it went offline or was lost.
1059    pub offline_at: Option<Timestamp>,
1060    /// Drained for maintenance (`schedr workers drain`): no new tasks until resumed.
1061    pub drained: bool,
1062    /// What is wrong with it now, as it last reported (e.g. a disabled fork server).
1063    #[serde(default)]
1064    pub warnings: Vec<WarningView>,
1065    /// The master it registered with last (a master's ID, as on `GET /api/v1/deployment`):
1066    /// kept while it is disconnected; none from an older agent's registration.
1067    #[serde(default, skip_serializing_if = "Option::is_none")]
1068    pub master_id: Option<String>,
1069    /// Its slots for wait steps.
1070    #[serde(default)]
1071    pub watcher_slots: u32,
1072    /// The processes running its wait steps, as its last heartbeat said (decision 343), and
1073    /// code sets whose hosts were lost.
1074    #[serde(default)]
1075    pub watcher_hosts: Vec<WatcherHostView>,
1076    /// Its memory as it last said (M5.1j, the Workers page's Memory column); none from an
1077    /// older worker, or one that hasn't said yet.
1078    #[serde(default, skip_serializing_if = "Option::is_none")]
1079    pub memory: Option<WorkerMemoryView>,
1080}
1081
1082/// A worker's memory, as it last said (at most a minute old while it heartbeats).
1083#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1084pub struct WorkerMemoryView {
1085    /// Its whole memory, in bytes: the agent, its fork servers, wait step hosts and running
1086    /// tasks.
1087    pub whole_bytes: u64,
1088    /// Its running tasks' together.
1089    pub tasks_bytes: u64,
1090    /// Its container's memory; none outside a cgroup v2.
1091    #[serde(default, skip_serializing_if = "Option::is_none")]
1092    pub container_bytes: Option<u64>,
1093    /// Its container's limit; none when unlimited.
1094    #[serde(default, skip_serializing_if = "Option::is_none")]
1095    pub container_limit_bytes: Option<u64>,
1096}
1097
1098impl From<&schedr_model::usage::WorkerUsage> for WorkerMemoryView {
1099    fn from(usage: &schedr_model::usage::WorkerUsage) -> Self {
1100        Self {
1101            whole_bytes: usage
1102                .process
1103                .resident_bytes
1104                .saturating_add(usage.fork_servers_bytes)
1105                .saturating_add(usage.watcher_hosts_bytes)
1106                .saturating_add(usage.tasks_bytes),
1107            tasks_bytes: usage.tasks_bytes,
1108            container_bytes: usage.process.container_bytes,
1109            container_limit_bytes: usage.process.container_limit_bytes,
1110        }
1111    }
1112}
1113
1114/// A process running a worker's wait steps, or a code set whose hosts were lost.
1115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1116pub struct WatcherHostView {
1117    /// The code it runs: its folders' names, the copies' hashes.
1118    pub code: String,
1119    /// The wait steps on it (none: no host runs this code now).
1120    pub wait_steps: u32,
1121    /// Its process's threads, the wait steps' among them.
1122    pub threads: u32,
1123    /// Those a wait step is tied to: running its `to_thread` calls, or started by it. The rest
1124    /// of the process, a library's pools among them, can't be told apart.
1125    pub tied_threads: u32,
1126    /// The memory it uses.
1127    pub memory_bytes: u64,
1128    /// Hosts of this code lost since the agent started: crashes and memory kills.
1129    pub hosts_lost: u64,
1130}
1131
1132/// Something wrong with a worker.
1133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1134pub struct WarningView {
1135    /// What kind: `fork_server_disabled`.
1136    pub kind: String,
1137    /// The interpreter it concerns; empty if none.
1138    pub interpreter: String,
1139    /// What it means for tasks.
1140    pub message: String,
1141}
1142
1143impl From<&WorkerRecord> for WorkerView {
1144    fn from(worker: &WorkerRecord) -> Self {
1145        Self {
1146            worker_id: worker.id.clone(),
1147            state: worker.state.to_string(),
1148            incarnation_id: worker.incarnation.clone(),
1149            queues: worker.queues.clone(),
1150            slots: worker.slots,
1151            running: worker.running,
1152            schedr_version: worker.schedr_version.clone(),
1153            protocol_version: worker.protocol_version.clone(),
1154            log_endpoint: worker.log_endpoint.clone(),
1155            registered_at: worker.registered_at,
1156            last_heartbeat_at: worker.last_heartbeat_at,
1157            offline_at: worker.offline_at,
1158            drained: worker.drained,
1159            warnings: worker
1160                .warnings
1161                .iter()
1162                .map(|w| WarningView {
1163                    kind: w.kind.clone(),
1164                    interpreter: w.interpreter.clone(),
1165                    message: mask_text(&w.message),
1166                })
1167                .collect(),
1168            master_id: None,
1169            memory: None,
1170            watcher_slots: worker.watcher_slots,
1171            watcher_hosts: worker
1172                .watcher_hosts
1173                .iter()
1174                .map(|host| WatcherHostView {
1175                    code: host.code.clone(),
1176                    wait_steps: host.wait_steps,
1177                    threads: host.threads,
1178                    tied_threads: host.tied_threads,
1179                    memory_bytes: host.memory_bytes,
1180                    hosts_lost: host.hosts_lost,
1181                })
1182                .collect(),
1183        }
1184    }
1185}
1186
1187/// The deployment this webserver serves, as nodes (decisions 121-123): its own, its masters
1188/// (leader and standbys) and its workers, each with its effective configuration, masked by the
1189/// node itself before it left its process (no secret in clear).
1190#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1191pub struct DeploymentView {
1192    /// The webserver answering (one of the deployment's, if it has several).
1193    pub webserver: NodeView,
1194    /// The masters heard from lately: the leader (the lease's holder) first.
1195    pub masters: Vec<MasterView>,
1196    /// Every worker the master has seen, gone ones included.
1197    pub workers: Vec<WorkerNodeView>,
1198    /// Who this request was made as, as the webserver sees it (`anonymous` without
1199    /// authentication; the person the web UI passed on, from the UI).
1200    pub user: String,
1201}
1202
1203/// A process of the deployment.
1204#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1205pub struct NodeView {
1206    /// The process (shared by a master and a worker in standalone).
1207    pub process_id: String,
1208    /// Its host.
1209    pub host: String,
1210    /// Its schedr version.
1211    pub schedr_version: String,
1212    /// Its effective configuration, masked.
1213    #[schema(value_type = Object)]
1214    pub config: serde_json::Value,
1215    /// What its process uses (decision 463): the webserver's now, a master's as its row last
1216    /// said; none when not known (no `/proc`, an older node).
1217    #[serde(default, skip_serializing_if = "Option::is_none")]
1218    pub usage: Option<NodeUsageView>,
1219}
1220
1221/// A schedr process's memory and CPU, and its container's (decision 463).
1222#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1223pub struct NodeUsageView {
1224    /// Resident memory, in bytes.
1225    pub resident_bytes: u64,
1226    /// CPU time used (user and system) since it started, in seconds.
1227    pub cpu_seconds: f64,
1228    /// Its cgroup's memory now; none outside a cgroup v2.
1229    #[serde(default, skip_serializing_if = "Option::is_none")]
1230    pub container_bytes: Option<u64>,
1231    /// Its container's memory limit; none when unlimited.
1232    #[serde(default, skip_serializing_if = "Option::is_none")]
1233    pub container_limit_bytes: Option<u64>,
1234}
1235
1236impl From<schedr_model::usage::NodeUsage> for NodeUsageView {
1237    fn from(usage: schedr_model::usage::NodeUsage) -> Self {
1238        Self {
1239            resident_bytes: usage.resident_bytes,
1240            cpu_seconds: usage.cpu_seconds,
1241            container_bytes: usage.container_bytes,
1242            container_limit_bytes: usage.container_limit_bytes,
1243        }
1244    }
1245}
1246
1247/// A worker's memory by part (decision 463), as it last said (written at most once a minute).
1248#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1249pub struct WorkerUsageView {
1250    /// The agent's own process (in standalone the master's and the webserver's too).
1251    pub process: NodeUsageView,
1252    /// Its fork servers', together.
1253    pub fork_servers_bytes: u64,
1254    /// Its wait step hosts', together.
1255    pub watcher_hosts_bytes: u64,
1256    /// Its running tasks', together.
1257    pub tasks_bytes: u64,
1258    /// The largest of them, largest first.
1259    #[serde(default)]
1260    pub largest_tasks: Vec<TaskMemoryView>,
1261}
1262
1263/// A running task's memory, named.
1264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1265pub struct TaskMemoryView {
1266    /// The attempt.
1267    pub attempt_id: String,
1268    /// Its DAG.
1269    pub dag_id: String,
1270    /// Its run.
1271    pub run_id: String,
1272    /// Its task.
1273    pub task_id: String,
1274    /// Its map index; none for an unmapped task.
1275    #[serde(default, skip_serializing_if = "Option::is_none")]
1276    pub map_index: Option<u32>,
1277    /// Its memory, in bytes.
1278    pub bytes: u64,
1279}
1280
1281impl From<schedr_model::usage::WorkerUsage> for WorkerUsageView {
1282    fn from(usage: schedr_model::usage::WorkerUsage) -> Self {
1283        Self {
1284            process: usage.process.into(),
1285            fork_servers_bytes: usage.fork_servers_bytes,
1286            watcher_hosts_bytes: usage.watcher_hosts_bytes,
1287            tasks_bytes: usage.tasks_bytes,
1288            largest_tasks: usage
1289                .largest_tasks
1290                .into_iter()
1291                .map(TaskMemoryView::from)
1292                .collect(),
1293        }
1294    }
1295}
1296
1297impl From<schedr_model::usage::TaskMemory> for TaskMemoryView {
1298    fn from(t: schedr_model::usage::TaskMemory) -> Self {
1299        Self {
1300            attempt_id: t.attempt_id,
1301            dag_id: t.dag_id,
1302            run_id: t.run_id,
1303            task_id: t.task_id,
1304            map_index: t.map_index,
1305            bytes: t.bytes,
1306        }
1307    }
1308}
1309
1310/// Samples of each process over a range (decisions 464, 465), in buckets: the Metrics page's
1311/// charts.
1312#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1313pub struct SampleSeriesList {
1314    /// The range asked: `1h`, `24h`, `7d` or `30d`.
1315    pub range: String,
1316    /// Each point's width, in seconds.
1317    pub step_s: u32,
1318    /// The range's start (the first bucket's).
1319    pub from: Timestamp,
1320    /// Its end: when it was asked.
1321    pub to: Timestamp,
1322    /// Each process sampled in it, by ID.
1323    pub processes: Vec<ProcessSamplesView>,
1324    /// The minutes the deployment was sampled in each bucket (asked for every process): a
1325    /// deployment's total in a bucket is its processes' averages weighted by their minutes over
1326    /// these, so a process replaced within a bucket isn't counted twice.
1327    #[serde(default)]
1328    pub coverage: Vec<CoverageView>,
1329}
1330
1331/// The minutes the deployment was sampled in a bucket.
1332#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1333pub struct CoverageView {
1334    /// The bucket's start.
1335    pub at: Timestamp,
1336    /// Its minutes in which any process was sampled.
1337    pub minutes: u32,
1338}
1339
1340/// A process's points over a range.
1341#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1342pub struct ProcessSamplesView {
1343    /// The process.
1344    pub process_id: String,
1345    /// What it runs (`master`, `worker`, `webserver`), each with its node's ID, as sampled
1346    /// last.
1347    pub roles: BTreeMap<String, String>,
1348    /// Its buckets with samples, oldest first.
1349    pub points: Vec<SamplePointView>,
1350    /// Its container's memory limit as its latest sample says; none when unlimited (or not
1351    /// in a container).
1352    #[serde(default, skip_serializing_if = "Option::is_none")]
1353    pub container_limit: Option<u64>,
1354    /// A worker's memory by part and its largest tasks, as sampled last (within a few
1355    /// minutes); none for another process.
1356    #[serde(default, skip_serializing_if = "Option::is_none")]
1357    pub parts: Option<WorkerPartsView>,
1358    /// Whether it has ended: no sample within three of the master's sample intervals before
1359    /// the samples were asked for (stopped, restarted as a new process, or lost).
1360    #[serde(default)]
1361    pub ended: bool,
1362}
1363
1364/// A bucket of a process's samples: averages and peaks.
1365#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1366pub struct SamplePointView {
1367    /// The bucket's start.
1368    pub at: Timestamp,
1369    /// Resident memory, in bytes, on average: the process itself.
1370    pub resident_avg: u64,
1371    /// The highest.
1372    pub resident_peak: u64,
1373    /// Its whole memory, in bytes, on average: itself and, for a worker, its fork servers,
1374    /// wait step hosts and running tasks.
1375    pub memory_avg: u64,
1376    /// The highest.
1377    pub memory_peak: u64,
1378    /// The minutes this process was sampled in the bucket: its averages' weight in a
1379    /// deployment's total (see [`SampleSeriesList::coverage`]).
1380    pub minutes: u32,
1381    /// Cores used, on average; none before a second sample.
1382    #[serde(default, skip_serializing_if = "Option::is_none")]
1383    pub cpu_avg: Option<f64>,
1384    /// The highest minute's.
1385    #[serde(default, skip_serializing_if = "Option::is_none")]
1386    pub cpu_peak: Option<f64>,
1387    /// Its container's memory, on average; none outside a cgroup v2.
1388    #[serde(default, skip_serializing_if = "Option::is_none")]
1389    pub container_avg: Option<u64>,
1390    /// The highest.
1391    #[serde(default, skip_serializing_if = "Option::is_none")]
1392    pub container_peak: Option<u64>,
1393    /// Its container's highest limit in the bucket; none when unlimited.
1394    #[serde(default, skip_serializing_if = "Option::is_none")]
1395    pub container_limit: Option<u64>,
1396    /// A worker's parts on average over the bucket's minutes (0 where it ran no worker).
1397    #[serde(default, skip_serializing_if = "Option::is_none")]
1398    pub parts: Option<PartsPointView>,
1399}
1400
1401/// A worker's memory by part in a bucket, on average.
1402#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1403pub struct PartsPointView {
1404    /// Its fork servers'.
1405    pub fork_servers_bytes: u64,
1406    /// Its wait step hosts'.
1407    pub watcher_hosts_bytes: u64,
1408    /// Its running tasks'.
1409    pub tasks_bytes: u64,
1410}
1411
1412/// A worker's memory by part and its largest tasks.
1413#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1414pub struct WorkerPartsView {
1415    /// When sampled.
1416    pub at: Timestamp,
1417    /// Its fork servers', together.
1418    pub fork_servers_bytes: u64,
1419    /// Its wait step hosts', together.
1420    pub watcher_hosts_bytes: u64,
1421    /// Its running tasks', together.
1422    pub tasks_bytes: u64,
1423    /// The largest of them, largest first.
1424    #[serde(default)]
1425    pub largest_tasks: Vec<TaskMemoryView>,
1426}
1427
1428/// Every process's memory together over a range (decision 462's sparkline).
1429#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1430pub struct MemoryTotals {
1431    /// Each point's width, in seconds.
1432    pub step_s: u32,
1433    /// The range's start.
1434    pub from: Timestamp,
1435    /// Its end: when it was asked.
1436    pub to: Timestamp,
1437    /// The whole memory, in bytes, of each bucket with samples, oldest first: the
1438    /// average of its minutes'.
1439    pub points: Vec<MemoryPointView>,
1440}
1441
1442/// A bucket's total memory.
1443#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1444pub struct MemoryPointView {
1445    /// The bucket's start.
1446    pub at: Timestamp,
1447    /// Every process's whole memory together, in bytes.
1448    pub resident: u64,
1449}
1450
1451/// A problem a node has now (decision 129): shown on its node, yellow for a warning, red for
1452/// an error.
1453#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1454pub struct ProblemView {
1455    /// An error; a warning otherwise.
1456    pub error: bool,
1457    /// What it is, for people.
1458    pub message: String,
1459}
1460
1461impl From<schedr_db::nodes::NodeProblem> for ProblemView {
1462    fn from(problem: schedr_db::nodes::NodeProblem) -> Self {
1463        Self {
1464            error: problem.error,
1465            message: mask_text(&problem.message),
1466        }
1467    }
1468}
1469
1470/// A master, leading or standing by.
1471#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1472pub struct MasterView {
1473    /// Its ID: the lease holder it takes the lease as.
1474    pub master_id: String,
1475    /// `leader` (it holds the lease) or `standby`.
1476    pub role: String,
1477    /// Where it runs, and its configuration.
1478    #[serde(flatten)]
1479    pub node: NodeView,
1480    /// When it started.
1481    pub started_at: Timestamp,
1482    /// When it was last heard from (it writes its row every 10 s).
1483    pub heard_at: Timestamp,
1484    /// Its problems as it last wrote them: its lease renewed late, a round failing, its
1485    /// command notifications failing.
1486    #[serde(default)]
1487    pub problems: Vec<ProblemView>,
1488}
1489
1490/// A worker as a node of the deployment.
1491#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1492pub struct WorkerNodeView {
1493    /// Its ID.
1494    pub worker_id: String,
1495    /// `active`, `draining`, `disconnected`, `offline` or `lost`.
1496    pub state: String,
1497    /// Its schedr version.
1498    pub schedr_version: String,
1499    /// The master it registered with last; none from an older agent.
1500    pub master_id: Option<String>,
1501    /// The process it runs in; none from an older agent.
1502    pub process_id: Option<String>,
1503    /// Its effective configuration, masked; none from an older agent.
1504    #[schema(value_type = Option<Object>)]
1505    pub config: Option<serde_json::Value>,
1506    /// The queues it serves.
1507    #[serde(default)]
1508    pub queues: Vec<String>,
1509    /// Its task slots (decision 462; 0 from an older webserver).
1510    #[serde(default)]
1511    pub slots: u32,
1512    /// Its attempts still running.
1513    #[serde(default)]
1514    pub running: u32,
1515    /// What it uses, by part, as it last said (decision 463); none from an older worker.
1516    #[serde(default, skip_serializing_if = "Option::is_none")]
1517    pub usage: Option<WorkerUsageView>,
1518    /// Its problems now: lost or offline (errors), what it reports wrong, the import errors
1519    /// of files it parsed (warnings).
1520    #[serde(default)]
1521    pub problems: Vec<ProblemView>,
1522}
1523
1524impl From<schedr_db::nodes::MasterRecord> for MasterView {
1525    fn from(master: schedr_db::nodes::MasterRecord) -> Self {
1526        Self {
1527            master_id: master.master_id,
1528            role: if master.leading { "leader" } else { "standby" }.to_owned(),
1529            node: NodeView {
1530                process_id: master.process_id,
1531                host: master.host,
1532                schedr_version: master.schedr_version,
1533                config: master.config,
1534                usage: master.usage.map(NodeUsageView::from),
1535            },
1536            started_at: master.started_at,
1537            heard_at: master.heard_at,
1538            problems: master.problems.into_iter().map(ProblemView::from).collect(),
1539        }
1540    }
1541}
1542
1543/// A file of a DAG root's current code that failed to import (decision 66).
1544#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1545pub struct ImportErrorView {
1546    /// The DAG root.
1547    pub root: String,
1548    /// The file, relative to the root.
1549    pub path: String,
1550    /// The root's content hash that was parsed.
1551    pub content_hash: String,
1552    /// When it was parsed.
1553    pub parsed_at: Timestamp,
1554    /// The worker that parsed it.
1555    pub worker_id: String,
1556    /// The master that stored the parse; none when not known (stored before it was kept).
1557    #[serde(default, skip_serializing_if = "Option::is_none")]
1558    pub master_id: Option<String>,
1559    /// That worker's schedr version.
1560    pub schedr_version: String,
1561    /// The exception's class name (`ParseTimeout`, `RunnerDied` or `ParseResultTooLarge` when
1562    /// the worker stopped the file; `InvalidDag` when the master refused a DAG).
1563    pub exception: String,
1564    /// The message.
1565    pub message: String,
1566    /// The traceback's last lines.
1567    pub traceback: String,
1568}
1569
1570impl From<&schedr_db::dags::ImportErrorRecord> for ImportErrorView {
1571    fn from(record: &schedr_db::dags::ImportErrorRecord) -> Self {
1572        Self {
1573            root: record.root.clone(),
1574            path: record.path.clone(),
1575            content_hash: record.content_hash.clone(),
1576            parsed_at: record.parsed_at,
1577            worker_id: record.worker_id.clone(),
1578            master_id: record.master_id.clone(),
1579            schedr_version: record.schedr_version.clone(),
1580            exception: record.error.exception.clone(),
1581            message: mask_text(&record.error.message),
1582            traceback: mask_text(&record.error.traceback),
1583        }
1584    }
1585}
1586
1587/// The import errors of each DAG root's current code.
1588#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1589pub struct ImportErrorList {
1590    /// By root, then path.
1591    pub errors: Vec<ImportErrorView>,
1592}
1593
1594/// Each DAG root's connections, in its current code (decision 211): what the UI lists, never
1595/// a value.
1596#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1597pub struct ConnectionList {
1598    /// By root.
1599    pub roots: Vec<RootConnections>,
1600}
1601
1602/// One root's connections.
1603#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1604pub struct RootConnections {
1605    /// The DAG root.
1606    pub root: String,
1607    /// By name: those its files define, and those its tasks declare without one.
1608    pub connections: Vec<ConnectionInfo>,
1609}
1610
1611/// A connection, as its root's current parse records it.
1612#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1613pub struct ConnectionInfo {
1614    /// Its name.
1615    pub name: String,
1616    /// A typed connection's type (`http`, `ssh`, `mongo`, `sql`, `generic`); none for a
1617    /// `@connection` function, or one that can't be used.
1618    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
1619    pub kind: Option<String>,
1620    /// The file defining it, relative to the root.
1621    #[serde(default, skip_serializing_if = "Option::is_none")]
1622    pub file: Option<String>,
1623    /// Why it can't be used: defined twice, invalid, or defined nowhere (a task declares it).
1624    #[serde(default, skip_serializing_if = "Option::is_none")]
1625    pub refused: Option<String>,
1626    /// The DAGs whose tasks declare it, by DAG.
1627    #[serde(default)]
1628    pub used_by: Vec<ConnectionUse>,
1629}
1630
1631/// The tasks of one DAG declaring a connection.
1632#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1633pub struct ConnectionUse {
1634    /// The DAG.
1635    pub dag_id: String,
1636    /// Its tasks declaring it, in the DAG's order.
1637    pub tasks: Vec<String>,
1638}
1639
1640impl ConnectionList {
1641    /// The list of each root's `registries` (root to its current parse's), with the tasks of
1642    /// `dags` (their current versions, those not removed) declaring each.
1643    #[must_use]
1644    pub fn of(
1645        registries: &std::collections::BTreeMap<String, schedr_model::connection::Registry>,
1646        dags: &[StoredDag],
1647    ) -> Self {
1648        use std::collections::BTreeMap;
1649        // Root, then connection, then DAG: its tasks.
1650        let mut uses: BTreeMap<&str, BTreeMap<&str, BTreeMap<String, Vec<String>>>> =
1651            BTreeMap::new();
1652        for dag in dags.iter().filter(|d| !d.removed) {
1653            let Some(current) = &dag.current else {
1654                continue;
1655            };
1656            let root = current.dag.location.root.as_str();
1657            for task in &current.dag.tasks {
1658                for name in &task.connections {
1659                    uses.entry(root)
1660                        .or_default()
1661                        .entry(name.as_str())
1662                        .or_default()
1663                        .entry(dag.dag_id.to_string())
1664                        .or_default()
1665                        .push(task.id.to_string());
1666                }
1667            }
1668        }
1669        let empty = schedr_model::connection::Registry::default();
1670        let mut roots: Vec<&str> = registries.keys().map(String::as_str).collect();
1671        roots.extend(uses.keys().filter(|r| !registries.contains_key(**r)));
1672        roots.sort_unstable();
1673        roots.dedup();
1674        let mut list = Self::default();
1675        for root in roots {
1676            let registry = registries.get(root).unwrap_or(&empty);
1677            let declared = uses.get(root);
1678            let mut names: Vec<&str> = registry.names().map(String::as_str).collect();
1679            names.extend(declared.into_iter().flat_map(|d| d.keys().copied()));
1680            names.sort_unstable();
1681            names.dedup();
1682            if names.is_empty() {
1683                continue;
1684            }
1685            let connections = names
1686                .into_iter()
1687                .map(|name| {
1688                    let found = registry.get(name);
1689                    ConnectionInfo {
1690                        name: name.to_owned(),
1691                        kind: found
1692                            .as_ref()
1693                            .ok()
1694                            .and_then(|def| def.kind)
1695                            .map(connection_type),
1696                        file: registry.files.get(name).cloned(),
1697                        refused: found.err(),
1698                        used_by: declared
1699                            .and_then(|d| d.get(name))
1700                            .map(|by_dag| {
1701                                by_dag
1702                                    .iter()
1703                                    .map(|(dag_id, tasks)| ConnectionUse {
1704                                        dag_id: dag_id.clone(),
1705                                        tasks: tasks.clone(),
1706                                    })
1707                                    .collect()
1708                            })
1709                            .unwrap_or_default(),
1710                    }
1711                })
1712                .collect();
1713            list.roots.push(RootConnections {
1714                root: root.to_owned(),
1715                connections,
1716            });
1717        }
1718        list
1719    }
1720}
1721
1722/// A connection type as the DAG JSON writes it.
1723fn connection_type(kind: schedr_model::connection::ConnectionType) -> String {
1724    use schedr_model::connection::ConnectionType;
1725    match kind {
1726        ConnectionType::Http => "http",
1727        ConnectionType::Ssh => "ssh",
1728        ConnectionType::Mongo => "mongo",
1729        ConnectionType::Sql => "sql",
1730        ConnectionType::Generic => "generic",
1731        ConnectionType::Schedr => "schedr",
1732    }
1733    .to_owned()
1734}
1735
1736/// The workers.
1737#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1738pub struct WorkerList {
1739    /// Every worker the master has seen, in ID order.
1740    pub workers: Vec<WorkerView>,
1741}
1742
1743/// A task's last ended attempts' peak memory (decision 467): the task panel's chart.
1744#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1745pub struct AttemptMemoryList {
1746    /// The task.
1747    pub task_id: String,
1748    /// Its memory budget in the DAG's current version (`memory=`), in bytes; none: the
1749    /// worker's share, which differs by worker.
1750    pub limit_bytes: Option<u64>,
1751    /// Its last ended attempts, all its runs and instances, the oldest first.
1752    pub attempts: Vec<AttemptMemoryView>,
1753}
1754
1755/// An ended attempt's peak memory.
1756#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1757pub struct AttemptMemoryView {
1758    /// The attempt.
1759    pub attempt_id: String,
1760    /// Its run.
1761    pub run_id: String,
1762    /// Its instance of a mapped task; none for a task that isn't mapped.
1763    pub map_index: Option<u32>,
1764    /// Its try.
1765    pub try_number: u32,
1766    /// How it ended (`success`, `oom_killed`, ...).
1767    pub status: String,
1768    /// Its peak memory (the watchdog's PSS), in bytes; none when it wasn't read.
1769    pub peak_memory_bytes: Option<u64>,
1770    /// When it ended.
1771    pub ended_at: Timestamp,
1772}
1773
1774/// Each task's p95 peak memory over its recent attempts against its limit (decision 467):
1775/// the DAG page's table.
1776#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1777pub struct DagMemoryList {
1778    /// Attempts ended since this (30 days before the request), of the DAG's 1000 runs ended
1779    /// last since then and those still going, are counted.
1780    pub since: Timestamp,
1781    /// The tasks with such attempts: those with a limit closest to it first, then the
1782    /// others by their p95, highest first.
1783    pub tasks: Vec<TaskPeakView>,
1784}
1785
1786/// A task's peaks.
1787#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1788pub struct TaskPeakView {
1789    /// The task.
1790    pub task_id: String,
1791    /// The attempts counted: those with a peak, the newest 1000 at most.
1792    pub attempts: u32,
1793    /// The 95th percentile of their peaks (nearest rank), in bytes.
1794    pub p95_bytes: u64,
1795    /// The highest, in bytes.
1796    pub max_bytes: u64,
1797    /// Of them, how many were killed for their memory.
1798    pub oom_killed: u32,
1799    /// Its memory budget in the DAG's current version, in bytes; none: the worker's share.
1800    pub limit_bytes: Option<u64>,
1801    /// `p95_bytes` over `limit_bytes`; none without a limit.
1802    pub of_limit: Option<f64>,
1803}
1804
1805/// The attempts of a range in buckets (decision 494): how many ended, by how, and how long
1806/// those started took from their assignment.
1807#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1808pub struct TaskFlowList {
1809    /// The range asked: `1h`, `24h`, `7d` or `30d`.
1810    pub range: String,
1811    /// Each point's width, in seconds.
1812    pub step_s: u32,
1813    /// The range's start (the first bucket's).
1814    pub from: Timestamp,
1815    /// Its end: when it was asked.
1816    pub to: Timestamp,
1817    /// Every bucket of the range, oldest first, empty ones included.
1818    pub buckets: Vec<TaskFlowView>,
1819}
1820
1821/// One bucket's attempts.
1822#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1823pub struct TaskFlowView {
1824    /// The bucket's start.
1825    pub at: Timestamp,
1826    /// Attempts that ended in it and succeeded.
1827    pub succeeded: u64,
1828    /// Those that failed: `failed`, `timed_out`, `oom_killed`.
1829    pub failed: u64,
1830    /// Those stopped by something else: `cancelled`, `interrupted`, `lost`,
1831    /// `assignment_expired`.
1832    pub stopped: u64,
1833    /// Attempts that started in it.
1834    pub started: u64,
1835    /// Their median time from assignment to start, in milliseconds (none: none started).
1836    pub start_p50_ms: Option<u64>,
1837    /// Their 95th percentile, in milliseconds.
1838    pub start_p95_ms: Option<u64>,
1839}