Skip to main content

schedr_bin/
user.rs

1//! The user CLI's commands over the REST API: `schedr dags ...`, `schedr runs ...`, `schedr
2//! tasks ...` and `schedr workers ...`.
3//!
4//! Human output is aligned columns with times in UTC and local time; `--json` prints the API's
5//! JSON (UTC only). Actions wait for the master's decision and print the result, or fail with
6//! the master's reason (see archive/PROJECT.md, Web UI and CLI).
7
8use std::io::Write;
9
10use jiff::tz::TimeZone;
11use schedr_api::views::{
12    AttemptView, BackfillRequest, CheckConnectionsRequest, CommandView, DagView, PostEventRequest,
13    RunDetail, RunView, TaskView, TestConnectionRequest, TriggerRequest, TriggerState, TriggerView,
14    WorkerView,
15};
16
17use crate::app::AppError;
18use crate::cli::{
19    ConnectionsCommand, DagsCommand, EventsCommand, LogsArgs, ResourcesCommand, RunsCommand,
20    SensorsCommand, TasksCommand, TriggersCommand, WorkersCommand,
21};
22use crate::client::{Client, TaskAction, Transport, WorkerAction};
23use crate::times::{parse_for, parse_time_flag, show, show_short, trigger_text};
24use schedr_model::commands::{ConnectionsResult, JobState, MAX_CONNECTION_TEST_MS, SecretState};
25
26#[cfg(test)]
27mod tests;
28
29/// How output is written.
30#[derive(Debug, Clone)]
31pub struct Output {
32    /// Print the API's JSON instead of text.
33    pub json: bool,
34    /// The machine's time zone, for the local half of times.
35    pub local: TimeZone,
36}
37
38/// Runs a `schedr dags` command.
39///
40/// # Errors
41///
42/// [`AppError::Client`] if the server can't be reached, answers with an error or rejects the
43/// command; [`AppError::BadArgument`] for `check` / `test`, which run locally
44/// ([`crate::local`]).
45pub async fn run_dags<T: Transport>(
46    command: &DagsCommand,
47    client: &Client<T>,
48    output: &Output,
49    out: &mut impl Write,
50) -> Result<(), AppError> {
51    match command {
52        DagsCommand::List => {
53            let dags = client.dags().await?;
54            if output.json {
55                return print_json(out, &dags);
56            }
57            write_table(
58                out,
59                &["DAG", "STATE", "HELD", "TRIGGER", "DEFINED IN"],
60                &dag_rows(&dags.dags, &output.local),
61            )?;
62            // Why each held DAG gets no runs, and what to do (decision 72.3).
63            for held in dags.dags.iter().filter_map(|d| d.held.as_ref()) {
64                writeln!(out, "\n{}", held.reason)?;
65            }
66        }
67        DagsCommand::Pause { dag } => {
68            let command = client
69                .wait(
70                    client
71                        .send_command(|| client.set_paused(dag, true, false))
72                        .await?,
73                )
74                .await?;
75            done(out, output, &command, &format!("paused {dag}"))?;
76        }
77        DagsCommand::Unpause { dag } => {
78            let command = client
79                .wait(
80                    client
81                        .send_command(|| client.set_paused(dag, false, false))
82                        .await?,
83                )
84                .await?;
85            done(out, output, &command, &format!("unpaused {dag}"))?;
86        }
87        DagsCommand::Check { .. } | DagsCommand::Test { .. } => {
88            return Err(AppError::BadArgument(
89                "`dags check` and `dags test` run locally, not against a server".to_owned(),
90            ));
91        }
92    }
93    Ok(())
94}
95
96/// Runs a `schedr workers` command (`list`; draining comes with M2.6).
97///
98/// # Errors
99///
100/// [`AppError::Client`] as for [`run_dags`] (a rejection carries the master's reason).
101pub async fn run_sensors<T: Transport>(
102    command: &SensorsCommand,
103    client: &Client<T>,
104    output: &Output,
105    out: &mut impl Write,
106) -> Result<(), AppError> {
107    match command {
108        SensorsCommand::SwitchedOff => {
109            let list = client.switched_off_sensors().await?;
110            if output.json {
111                return print_json(out, &list);
112            }
113            let rows: Vec<Vec<String>> = list
114                .sensors
115                .iter()
116                .map(|s| {
117                    vec![
118                        s.dag_id.clone(),
119                        s.sensor.clone(),
120                        s.strikes.to_string(),
121                        s.switched_off_at.clone(),
122                    ]
123                })
124                .collect();
125            write_table(out, &["DAG", "SENSOR", "STRIKES", "SWITCHED OFF"], &rows)?;
126            Ok(())
127        }
128        SensorsCommand::SwitchOn { dag, sensor } => {
129            let command = client
130                .wait(
131                    client
132                        .send_command(|| client.switch_on_sensor(dag, sensor))
133                        .await?,
134                )
135                .await?;
136            if output.json {
137                return print_json(out, &command);
138            }
139            writeln!(out, "switched on {dag} {sensor}")?;
140            Ok(())
141        }
142    }
143}
144
145/// `schedr triggers ...`.
146///
147/// # Errors
148///
149/// [`AppError::Client`] as for [`run_dags`] (a rejection carries the master's reason).
150pub async fn run_triggers<T: Transport>(
151    command: &TriggersCommand,
152    client: &Client<T>,
153    output: &Output,
154    out: &mut impl Write,
155) -> Result<(), AppError> {
156    match command {
157        TriggersCommand::List => {
158            let list = client.triggers().await?;
159            if output.json {
160                return print_json(out, &list);
161            }
162            write_table(
163                out,
164                &[
165                    "DAG",
166                    "TRIGGER",
167                    "STATE",
168                    "WORKER",
169                    "BOOKMARK",
170                    "FAILURES",
171                    "LAST ERROR",
172                ],
173                &list.triggers.iter().map(trigger_row).collect::<Vec<_>>(),
174            )?;
175        }
176        TriggersCommand::Show { dag } => {
177            let trigger = client.dag_trigger(dag).await?;
178            if output.json {
179                return print_json(out, &trigger);
180            }
181            write_table(
182                out,
183                &[
184                    "DAG",
185                    "TRIGGER",
186                    "STATE",
187                    "WORKER",
188                    "BOOKMARK",
189                    "FAILURES",
190                    "LAST ERROR",
191                ],
192                &[trigger_row(&trigger)],
193            )?;
194            for (what, at) in [
195                ("started", trigger.started_at),
196                ("last event", trigger.last_event_at),
197                ("last poked", trigger.last_poked_at),
198                ("last idle restart", trigger.last_restart_at),
199                ("not before", trigger.not_before),
200            ] {
201                if let Some(at) = at {
202                    writeln!(out, "{what}: {at}")?;
203                }
204            }
205            if let Some(why) = &trigger.stopped_why {
206                writeln!(out, "stopped: {}", one_line(why))?;
207            }
208            if let Some(run) = &trigger.called_for {
209                writeln!(out, "called for run: {run}")?;
210            }
211        }
212        TriggersCommand::Events { dag, limit } => {
213            let list = client.trigger_events(dag, *limit).await?;
214            if output.json {
215                return print_json(out, &list);
216            }
217            let rows: Vec<Vec<String>> = list
218                .events
219                .iter()
220                .map(|event| {
221                    vec![
222                        one_line(&event.key),
223                        event.received_at.to_string(),
224                        one_line(&event.data.to_string()),
225                    ]
226                })
227                .collect();
228            write_table(out, &["KEY", "RECEIVED", "DATA"], &rows)?;
229        }
230        TriggersCommand::Restart { dag }
231        | TriggersCommand::Skip { dag }
232        | TriggersCommand::SwitchOn { dag } => {
233            trigger_command(command, dag, client, output, out).await?;
234        }
235    }
236    Ok(())
237}
238
239/// `schedr triggers restart|skip|switch-on <dag>`: the command, waited for.
240async fn trigger_command<T: Transport>(
241    command: &TriggersCommand,
242    dag: &str,
243    client: &Client<T>,
244    output: &Output,
245    out: &mut impl Write,
246) -> Result<(), AppError> {
247    match command {
248        TriggersCommand::Restart { .. } => {
249            let command = client
250                .wait(client.send_command(|| client.restart_trigger(dag)).await?)
251                .await?;
252            if output.json {
253                return print_json(out, &command);
254            }
255            writeln!(out, "restarting the trigger of {dag}")?;
256        }
257        TriggersCommand::Skip { .. } => {
258            let command = client
259                .wait(client.send_command(|| client.skip_trigger_run(dag)).await?)
260                .await?;
261            if output.json {
262                return print_json(out, &command);
263            }
264            let run = command
265                .result
266                .as_ref()
267                .and_then(|result| result.get("run_id"))
268                .and_then(serde_json::Value::as_str)
269                .unwrap_or_default();
270            writeln!(out, "passed run {run} of the trigger of {dag}")?;
271        }
272        TriggersCommand::SwitchOn { .. } => {
273            let command = client
274                .wait(
275                    client
276                        .send_command(|| client.switch_on_trigger(dag))
277                        .await?,
278                )
279                .await?;
280            if output.json {
281                return print_json(out, &command);
282            }
283            writeln!(out, "switched on the trigger of {dag}")?;
284        }
285        TriggersCommand::List | TriggersCommand::Show { .. } | TriggersCommand::Events { .. } => {}
286    }
287    Ok(())
288}
289
290/// What a trigger said, on one line of a table and with nothing a terminal would act on.
291fn one_line(text: &str) -> String {
292    text.chars()
293        .map(|c| {
294            if schedr_model::trigger::acts_on_display(c) {
295                ' '
296            } else {
297                c
298            }
299        })
300        .collect()
301}
302
303fn trigger_row(trigger: &TriggerView) -> Vec<String> {
304    let shown = |text: &Option<String>| text.as_deref().map_or_else(|| "-".to_owned(), one_line);
305    vec![
306        trigger.dag_id.clone(),
307        trigger.trigger.clone(),
308        // Its worker may hang: `schedr triggers restart` starts it again.
309        if trigger.stuck {
310            format!("{} (stuck)", trigger.state)
311        } else {
312            trigger.state.clone()
313        },
314        shown(&trigger.worker),
315        shown(&trigger.bookmark),
316        trigger.failures.to_string(),
317        shown(&trigger.last_error),
318    ]
319}
320
321/// `schedr events ...` (decision 354).
322///
323/// # Errors
324///
325/// [`AppError::BadArgument`] for data that isn't JSON or a time that doesn't read;
326/// [`AppError::Client`] as for [`run_dags`].
327pub async fn run_events<T: Transport>(
328    command: &EventsCommand,
329    client: &Client<T>,
330    output: &Output,
331    out: &mut impl Write,
332    err: &mut impl Write,
333) -> Result<(), AppError> {
334    match command {
335        EventsCommand::Post {
336            name,
337            key,
338            data,
339            at,
340        } => {
341            let data = given_event_data(data.as_deref())
342                .map_err(|why| AppError::BadArgument(why.replace("--event-data", "--data")))?;
343            let request = PostEventRequest {
344                name: name.clone(),
345                key: key.clone(),
346                data: data.unwrap_or_default(),
347                at: for_time(at.as_deref(), err)?,
348            };
349            // One key for every try: a post whose answer was lost is stored once.
350            let event = client
351                .submit(schedr_client::new_command_key(), || {
352                    client.post_event(&request)
353                })
354                .await?;
355            if output.json {
356                return print_json(out, &event);
357            }
358            writeln!(
359                out,
360                "posted event {} ({name}, key {})",
361                event.id,
362                one_line(&event.key)
363            )?;
364        }
365        EventsCommand::List { name, limit } => {
366            let list = client.named_events(name.as_deref(), *limit).await?;
367            if output.json {
368                return print_json(out, &list);
369            }
370            let rows: Vec<Vec<String>> = list
371                .events
372                .iter()
373                .map(|event| {
374                    vec![
375                        event.name.clone(),
376                        one_line(&event.key),
377                        event.at.to_string(),
378                        one_line(&event.posted_by),
379                        one_line(&event.data.to_string()),
380                    ]
381                })
382                .collect();
383            write_table(out, &["NAME", "KEY", "AT", "POSTED BY", "DATA"], &rows)?;
384        }
385    }
386    Ok(())
387}
388
389/// `--event-data`: JSON, or `@file.json`.
390///
391/// # Errors
392///
393/// What is wrong with it.
394pub(crate) fn given_event_data(given: Option<&str>) -> Result<Option<serde_json::Value>, String> {
395    let Some(given) = given else {
396        return Ok(None);
397    };
398    let text = match given.strip_prefix('@') {
399        Some(path) => std::fs::read_to_string(path)
400            .map_err(|e| format!("--event-data: can't read `{path}`: {e}"))?,
401        None => given.to_owned(),
402    };
403    serde_json::from_str(&text)
404        .map(Some)
405        .map_err(|e| format!("--event-data must be JSON: {e}"))
406}
407
408/// `schedr resources ...`.
409///
410/// # Errors
411///
412/// [`AppError::Client`] as for [`run_dags`].
413pub async fn run_resources<T: Transport>(
414    command: &ResourcesCommand,
415    client: &Client<T>,
416    output: &Output,
417    out: &mut impl Write,
418) -> Result<(), AppError> {
419    let ResourcesCommand::List { run } = command;
420    let list = client.run_resources(run).await?;
421    if output.json {
422        return print_json(out, &list);
423    }
424    let rows: Vec<Vec<String>> = list
425        .resources
426        .iter()
427        .map(|r| {
428            vec![
429                r.setup.clone(),
430                r.cleanup.clone(),
431                r.state.clone(),
432                r.users.join(","),
433            ]
434        })
435        .collect();
436    write_table(out, &["RESOURCE", "CLEANUP", "STATE", "USERS"], &rows)?;
437    Ok(())
438}
439
440/// `schedr workers ...`.
441///
442/// # Errors
443///
444/// [`AppError::Client`] as for [`run_dags`] (a rejection carries the master's reason).
445pub async fn run_workers<T: Transport>(
446    command: &WorkersCommand,
447    client: &Client<T>,
448    output: &Output,
449    out: &mut impl Write,
450) -> Result<(), AppError> {
451    match command {
452        WorkersCommand::List => {
453            let workers = client.workers().await?;
454            if output.json {
455                return print_json(out, &workers);
456            }
457            let rows: Vec<Vec<String>> = workers
458                .workers
459                .iter()
460                .map(|w| worker_row(w, &output.local))
461                .collect();
462            write_table(
463                out,
464                &[
465                    "WORKER",
466                    "STATE",
467                    "RUNNING",
468                    "QUEUES",
469                    "LAST SEEN",
470                    "WARNINGS",
471                ],
472                &rows,
473            )?;
474            // The warnings themselves under the table: too long for a column.
475            for worker in &workers.workers {
476                for warning in &worker.warnings {
477                    writeln!(out, "{}: {}", worker.worker_id, warning.message)?;
478                }
479            }
480            Ok(())
481        }
482        WorkersCommand::Drain { worker } => {
483            let command = client
484                .wait(
485                    client
486                        .send_command(|| client.worker_action(worker, WorkerAction::Drain))
487                        .await?,
488                )
489                .await?;
490            let running = command
491                .result
492                .as_ref()
493                .and_then(|r| r["running"].as_u64())
494                .unwrap_or(0);
495            done(
496                out,
497                output,
498                &command,
499                &format!(
500                    "draining {worker}: no new tasks; {running} running task(s) finishing \
501                     (`schedr workers resume {worker}` to undo)"
502                ),
503            )
504        }
505        WorkersCommand::Resume { worker } => {
506            let command = client
507                .wait(
508                    client
509                        .send_command(|| client.worker_action(worker, WorkerAction::Resume))
510                        .await?,
511                )
512                .await?;
513            done(out, output, &command, &format!("resumed {worker}"))
514        }
515    }
516}
517
518/// Runs `schedr connections ...`: the command sent, then its result read back until every
519/// worker answered; a table of each connection, or the result as JSON.
520///
521/// # Errors
522///
523/// [`AppError::Client`] as for [`run_dags`]; [`AppError::Failed`] when a connection isn't
524/// fine, or a worker didn't answer.
525pub async fn run_connections<T: Transport>(
526    command: &ConnectionsCommand,
527    client: &Client<T>,
528    output: &Output,
529    out: &mut impl Write,
530) -> Result<(), AppError> {
531    // A test may take its timeout; past it and a margin, its worker won't answer.
532    let (sent, wait) = match command {
533        ConnectionsCommand::Check { root, name, worker } => {
534            let request = CheckConnectionsRequest {
535                root: root.clone(),
536                name: name.clone(),
537                worker: worker.clone(),
538            };
539            let sent = client
540                .send_command(|| client.check_connections(&request))
541                .await?;
542            (sent, CONNECTIONS_ANSWER_MARGIN)
543        }
544        ConnectionsCommand::Test {
545            name,
546            root,
547            worker,
548            timeout,
549        } => {
550            let request = TestConnectionRequest {
551                root: root.clone(),
552                worker: worker.clone(),
553                timeout_ms: timeout.map(|t| u64::try_from(t.as_millis()).unwrap_or(u64::MAX)),
554            };
555            let sent = client
556                .send_command(|| client.test_connection(name, &request))
557                .await?;
558            // Not given, it is the webserver's to say: the longest any test may take is waited
559            // for at most, and the job's end comes first.
560            let longest = std::time::Duration::from_millis(MAX_CONNECTION_TEST_MS);
561            (sent, timeout.unwrap_or(longest) + CONNECTIONS_ANSWER_MARGIN)
562        }
563    };
564    let applied = client.wait(sent).await?;
565    let result = client.wait_connections(applied, wait).await?;
566    if output.json {
567        print_json(out, &result)?;
568    } else {
569        write_connections(out, &result)?;
570    }
571    let bad = result
572        .jobs
573        .iter()
574        .map(|job| match job.state {
575            JobState::Done => job.connections.iter().filter(|c| !c.ok).count(),
576            _ => 1,
577        })
578        .sum::<usize>();
579    if bad > 0 {
580        return Err(AppError::Failed(format!(
581            "{bad} connection(s) or worker(s) not fine"
582        )));
583    }
584    Ok(())
585}
586
587/// How long past its own time a connections job's worker has to answer.
588const CONNECTIONS_ANSWER_MARGIN: std::time::Duration = std::time::Duration::from_secs(60);
589
590fn write_connections(out: &mut impl Write, result: &ConnectionsResult) -> Result<(), AppError> {
591    let mut rows = Vec::new();
592    let mut notes = Vec::new();
593    for job in &result.jobs {
594        if job.state != JobState::Done {
595            rows.push(vec![
596                job.root.clone(),
597                "-".to_owned(),
598                job.worker.clone(),
599                match job.state {
600                    JobState::Lost => "lost".to_owned(),
601                    _ => "no answer".to_owned(),
602                },
603            ]);
604            if let Some(reason) = &job.reason {
605                notes.push(format!("{}: {reason}", job.root));
606            }
607            continue;
608        }
609        for report in &job.connections {
610            let state = if report.ok { "ok" } else { "failed" };
611            let state = match report.duration_ms {
612                Some(ms) => format!("{state} ({}.{:01} s)", ms / 1000, ms % 1000 / 100),
613                None => state.to_owned(),
614            };
615            rows.push(vec![
616                job.root.clone(),
617                report.name.clone(),
618                job.worker.clone(),
619                state,
620            ]);
621            for secret in &report.secrets {
622                if secret.state != SecretState::Present {
623                    let state = serde_json::to_value(secret.state)
624                        .ok()
625                        .and_then(|v| v.as_str().map(str::to_owned))
626                        .unwrap_or_default();
627                    let why = secret
628                        .message
629                        .as_deref()
630                        .map(|m| format!(": {m}"))
631                        .unwrap_or_default();
632                    notes.push(format!(
633                        "{}: secret `{}` {state}{why}",
634                        report.name, secret.secret
635                    ));
636                }
637            }
638            if let Some(error) = &report.error {
639                notes.push(format!("{}: {error}", report.name));
640            }
641        }
642    }
643    write_table(out, &["ROOT", "CONNECTION", "WORKER", "STATE"], &rows)?;
644    for note in notes {
645        writeln!(out, "{note}")?;
646    }
647    Ok(())
648}
649
650fn worker_row(worker: &WorkerView, local: &TimeZone) -> Vec<String> {
651    vec![
652        worker.worker_id.clone(),
653        if worker.drained {
654            format!("{} (drained)", worker.state)
655        } else {
656            worker.state.clone()
657        },
658        format!("{}/{}", worker.running, worker.slots),
659        worker.queues.join(","),
660        show(worker.last_heartbeat_at, local),
661        worker.warnings.len().to_string(),
662    ]
663}
664
665/// Runs a `schedr runs` command; warnings (e.g. `--for` read as UTC) go to `err`.
666///
667/// # Errors
668///
669/// [`AppError::Client`] as for [`run_dags`], [`AppError::BadArgument`] for a `--for` that
670/// doesn't read.
671pub async fn run_runs<T: Transport>(
672    command: &RunsCommand,
673    client: &Client<T>,
674    output: &Output,
675    out: &mut impl Write,
676    err: &mut impl Write,
677) -> Result<(), AppError> {
678    match command {
679        RunsCommand::Trigger {
680            dag,
681            planned_for,
682            params,
683            params_json,
684            event,
685            event_key,
686            event_data,
687            event_at,
688        } => {
689            let params = given_params(params, params_json.as_deref())?;
690            let event_at = for_time(event_at.as_deref(), err)?;
691            let at = for_time(planned_for.as_deref(), err)?;
692            let request = TriggerRequest {
693                planned_for: at,
694                params,
695                event: event.clone(),
696                event_key: event_key.clone(),
697                event_data: given_event_data(event_data.as_deref())
698                    .map_err(AppError::BadArgument)?,
699                event_at,
700            };
701            let command = client
702                .wait(
703                    client
704                        .send_command(|| client.trigger_with(dag, &request))
705                        .await?,
706                )
707                .await?;
708            let run_id = command
709                .result
710                .as_ref()
711                .and_then(|r| r["run_id"].as_str())
712                .unwrap_or_default()
713                .to_owned();
714            if output.json {
715                return print_json(out, &command);
716            }
717            let run = client.run(&run_id).await?;
718            writeln!(
719                out,
720                "triggered run {run_id} of {dag} for {} ({})",
721                show(run.run.planned_for, &output.local),
722                run.run.state
723            )?;
724        }
725        RunsCommand::List { dag, planned_for } => {
726            let at = for_time(planned_for.as_deref(), err)?;
727            let runs = client.runs(dag, at).await?;
728            if output.json {
729                return print_json(out, &runs);
730            }
731            let rows: Vec<Vec<String>> = runs
732                .runs
733                .iter()
734                .map(|run| run_row(run, &output.local))
735                .collect();
736            write_table(out, &["RUN", "KIND", "STATE", "FOR", "BY"], &rows)?;
737        }
738        RunsCommand::Show { run_id } => {
739            let detail = client.run(run_id).await?;
740            if output.json {
741                return print_json(out, &detail);
742            }
743            print_run(&detail, &output.local, out)?;
744        }
745        RunsCommand::Cancel { run_id, backfill } => {
746            let Some(run_id) = run_id.as_deref().filter(|_| backfill.is_none()) else {
747                let backfill = backfill.as_deref().unwrap_or_default();
748                return cancel_backfill(client, output, backfill, out).await;
749            };
750            let command = client
751                .wait(client.send_command(|| client.cancel(run_id)).await?)
752                .await?;
753            let stopping = command
754                .result
755                .as_ref()
756                .and_then(|r| r["stopping_attempts"].as_u64())
757                .unwrap_or(0);
758            done(
759                out,
760                output,
761                &command,
762                &format!("cancelling run {run_id} ({stopping} running task(s) being stopped)"),
763            )?;
764        }
765        RunsCommand::Backfill { .. } => return backfill(command, client, output, out, err).await,
766    }
767    Ok(())
768}
769
770/// `schedr runs backfill`: waits for the master's decision, then says what it created, or
771/// would (decision 363).
772async fn backfill<T: Transport>(
773    command: &RunsCommand,
774    client: &Client<T>,
775    output: &Output,
776    out: &mut impl Write,
777    err: &mut impl Write,
778) -> Result<(), AppError> {
779    let RunsCommand::Backfill {
780        dag,
781        from,
782        to,
783        all,
784        params,
785        params_json,
786        dry_run,
787    } = command
788    else {
789        return Ok(());
790    };
791    let moment = |flag: &str, text: &str, err: &mut dyn Write| {
792        let parsed = parse_time_flag(flag, text).map_err(AppError::BadArgument)?;
793        if let Some(warning) = parsed.warning {
794            writeln!(err, "{warning}")?;
795        }
796        Ok::<_, AppError>(parsed.at)
797    };
798    let request = BackfillRequest {
799        from: moment("--from", from, err)?,
800        to: to
801            .as_deref()
802            .map(|to| moment("--to", to, err))
803            .transpose()?,
804        all: *all,
805        params: given_params(params, params_json.as_deref())?,
806        dry_run: *dry_run,
807    };
808    let command = client
809        .wait(
810            client
811                .send_command(|| client.backfill(dag, &request))
812                .await?,
813        )
814        .await?;
815    let result = command.result.clone().unwrap_or_default();
816    let count = |key: &str| result[key].as_u64().unwrap_or(0);
817    let (times, created, skipped) = (count("fire_times"), count("created"), count("skipped"));
818    let message = match result["backfill_id"].as_str() {
819        _ if *dry_run => format!(
820            "{times} fire time(s), {skipped} with a successful, queued or running run: \
821             would create {created} run(s) (dry run)"
822        ),
823        Some(id) => format!(
824            "backfill {id} of {dag}: {times} fire time(s), {skipped} skipped, \
825             {created} run(s) created"
826        ),
827        None => format!(
828            "nothing to backfill: each of the {times} fire time(s) has a successful, queued \
829             or running run (--all runs them again)"
830        ),
831    };
832    done(out, output, &command, &message)
833}
834
835/// `schedr runs cancel --backfill`: its queued and running runs (decision 402).
836async fn cancel_backfill<T: Transport>(
837    client: &Client<T>,
838    output: &Output,
839    backfill: &str,
840    out: &mut impl Write,
841) -> Result<(), AppError> {
842    let command = client
843        .wait(
844            client
845                .send_command(|| client.cancel_backfill(backfill))
846                .await?,
847        )
848        .await?;
849    let result = command.result.clone().unwrap_or_default();
850    let count = |key: &str| result[key].as_u64().unwrap_or(0);
851    done(
852        out,
853        output,
854        &command,
855        &format!(
856            "cancelling backfill {backfill}: {} run(s) ({} running task(s) being stopped)",
857            result["cancelled_runs"].as_array().map_or(0, Vec::len),
858            count("stopping_attempts")
859        ),
860    )
861}
862
863/// `schedr tasks cancel` and `retry`: each waits for the master's decision; `logs`,
864/// `attempts` and `output` read.
865///
866/// # Errors
867///
868/// [`AppError::Client`] as for [`run_dags`] (a rejection carries the master's reason).
869pub async fn run_tasks<T: Transport>(
870    command: &TasksCommand,
871    client: &Client<T>,
872    output: &Output,
873    out: &mut impl Write,
874) -> Result<(), AppError> {
875    let (target, action) = match command {
876        TasksCommand::Cancel(target) => (target, TaskAction::Cancel),
877        TasksCommand::Retry(target) => (target, TaskAction::Retry),
878        TasksCommand::Logs(args) => return print_log(args, client, output, out).await,
879        TasksCommand::Attempts(target) => {
880            let attempts = client
881                .instance_attempts(&target.run_id, &target.task_id, target.map_index)
882                .await?;
883            if output.json {
884                return print_json(out, &attempts);
885            }
886            let rows: Vec<Vec<String>> = attempts
887                .attempts
888                .iter()
889                .map(|attempt| attempt_row(attempt, &output.local))
890                .collect();
891            let headers = [
892                "TRY", "STATUS", "WORKER", "STARTED", "ENDED", "DURATION", "EXIT", "ERROR",
893            ];
894            return write_table(out, &headers, &rows);
895        }
896        TasksCommand::Output(target) => {
897            let found = client
898                .instance_output(&target.run_id, &target.task_id, target.map_index)
899                .await?;
900            // Text output is the value alone, ready for a pipe; `--json` adds the outcome.
901            return if output.json {
902                print_json(out, &found)
903            } else {
904                print_json(out, &found.value)
905            };
906        }
907    };
908    let (run_id, task_id) = (&target.run_id, &target.task_id);
909    let instance = (task_id.as_str(), target.map_index);
910    let command = client
911        .wait(
912            client
913                .send_command(|| client.task_action(run_id, instance, action))
914                .await?,
915        )
916        .await?;
917    let task_id = shown_task(task_id, target.map_index);
918    let state = command
919        .result
920        .as_ref()
921        .and_then(|r| r["state"].as_str())
922        .unwrap_or_default();
923    let message = match (action, state) {
924        (TaskAction::Cancel, "stopping") => {
925            format!("cancelling task {task_id} of run {run_id} (being stopped)")
926        }
927        (TaskAction::Cancel, _) => format!("cancelled task {task_id} of run {run_id}"),
928        (TaskAction::Retry, _) => format!("queued task {task_id} of run {run_id} again"),
929    };
930    done(out, output, &command, &message)
931}
932
933/// How a task (instance) ended with no attempt (`` `upstream_failed` ``, or its run's end), if
934/// it did: followed, its log would never come.
935async fn ended_untried<T: Transport>(
936    client: &Client<T>,
937    run_id: &str,
938    task_id: &str,
939    map_index: Option<u32>,
940) -> Result<Option<String>, AppError> {
941    let detail = client.run(run_id).await?;
942    let index = map_index.map_or(-1, |i| i32::try_from(i).unwrap_or(i32::MAX));
943    let state = detail
944        .tasks
945        .iter()
946        .find(|task| task.task_id == task_id && task.map_index == index)
947        .map(|task| task.state.as_str());
948    let final_task = state
949        .and_then(|state| serde_json::from_value(serde_json::Value::from(state)).ok())
950        .is_some_and(schedr_model::TaskInstanceState::is_final);
951    if final_task {
952        return Ok(state.map(|state| format!("`{state}`")));
953    }
954    let run_ended = matches!(
955        detail.run.state.as_str(),
956        "success" | "failed" | "cancelled"
957    );
958    Ok(run_ended.then(|| format!("(its run `{}`)", detail.run.state)))
959}
960
961/// `schedr tasks logs`: the attempt's log as it is, part by part (`--json`: each part as the
962/// API's JSON, one per line); with `--follow`, waiting for the attempt to start and on until
963/// it ends.
964async fn print_log<T: Transport>(
965    args: &LogsArgs,
966    client: &Client<T>,
967    output: &Output,
968    out: &mut impl Write,
969) -> Result<(), AppError> {
970    let target = &args.target;
971    let (run_id, task_id) = (target.run_id.as_str(), target.task_id.as_str());
972    let map_index = target.map_index;
973    let try_number = loop {
974        let attempts = client
975            .instance_attempts(run_id, task_id, map_index)
976            .await?
977            .attempts;
978        let attempt = match args.try_number {
979            Some(n) => attempts.into_iter().find(|a| a.try_number == n),
980            None => attempts.into_iter().max_by_key(|a| a.try_number),
981        };
982        match (attempt, args.try_number) {
983            // Assigned, not started yet: following waits for it.
984            (Some(a), _) if args.follow && a.started_at.is_none() && a.status.is_none() => {}
985            (Some(a), _) => break a.try_number,
986            // The API says what is missing.
987            (None, Some(n)) => break n,
988            // Waiting for its first attempt, unless it ended without one (B213).
989            (None, None) if args.follow => {
990                if let Some(ended) = ended_untried(client, run_id, task_id, map_index).await? {
991                    return Err(AppError::BadArgument(format!(
992                        "task `{task_id}` of run `{run_id}` ended {ended} without being tried: no log"
993                    )));
994                }
995            }
996            (None, None) => {
997                return Err(AppError::BadArgument(format!(
998                    "task `{task_id}` of run `{run_id}` hasn't been tried yet: no log so far"
999                )));
1000            }
1001        }
1002        tokio::time::sleep(client.poll()).await;
1003    };
1004    let mut from = 0;
1005    loop {
1006        let chunk = client
1007            .instance_log_part(
1008                run_id,
1009                (task_id, map_index),
1010                try_number,
1011                from,
1012                schedr_model::logs::MAX_CHUNK,
1013            )
1014            .await?;
1015        if output.json {
1016            let line =
1017                serde_json::to_string(&chunk).map_err(|e| AppError::BadArgument(e.to_string()))?;
1018            writeln!(out, "{line}")?;
1019        } else {
1020            out.write_all(chunk.content.as_bytes())?;
1021        }
1022        out.flush()?;
1023        let progressed = chunk.next > from;
1024        from = chunk.next;
1025        if from < chunk.size && progressed {
1026            continue;
1027        }
1028        if !(args.follow && chunk.running) {
1029            return Ok(());
1030        }
1031        tokio::time::sleep(client.poll()).await;
1032    }
1033}
1034
1035/// `schedr runs show`: the run, then its tasks; a mapped task's own row (with its instance
1036/// count) comes before its instances, `fetch[0]`, `fetch[1]`, ... (decision 86).
1037fn print_run(detail: &RunDetail, local: &TimeZone, out: &mut impl Write) -> Result<(), AppError> {
1038    let run = &detail.run;
1039    writeln!(
1040        out,
1041        "run {} of {} ({}) for {}: {}",
1042        run.run_id,
1043        run.dag_id,
1044        run.kind_label(),
1045        show(run.planned_for, local),
1046        run_state(run)
1047    )?;
1048    if detail.code_hashes.len() > 1 {
1049        // Its code changed while it ran.
1050        writeln!(out, "ran on code {}", detail.code_hashes.join(", "))?;
1051    }
1052    if let Some(params) = detail.params.as_object().filter(|p| !p.is_empty()) {
1053        // As given with `-p` (masked by the webserver, decision 134).
1054        let shown: Vec<String> = params
1055            .iter()
1056            .map(|(name, value)| match value {
1057                serde_json::Value::String(text) => format!("{name}={text}"),
1058                other => format!("{name}:={other}"),
1059            })
1060            .collect();
1061        writeln!(out, "params: {}", shown.join(" "))?;
1062    }
1063    let rows: Vec<Vec<String>> = detail.tasks.iter().map(task_row).collect();
1064    write_table(
1065        out,
1066        &["TASK", "STATE", "OUTCOME", "TRIES", "INSTANCES", "REASON"],
1067        &rows,
1068    )
1069}
1070
1071fn task_row(task: &TaskView) -> Vec<String> {
1072    let index = u32::try_from(task.map_index).ok();
1073    vec![
1074        shown_task(&task.task_id, index),
1075        task.state.clone(),
1076        task.outcome.clone().unwrap_or_default(),
1077        task.try_number.to_string(),
1078        task.instances.map_or_else(String::new, |n| n.to_string()),
1079        task.reason.clone().unwrap_or_default(),
1080    ]
1081}
1082
1083fn attempt_row(attempt: &AttemptView, local: &TimeZone) -> Vec<String> {
1084    let status = attempt.status.clone().unwrap_or_else(|| {
1085        if attempt.started_at.is_some() {
1086            "running"
1087        } else {
1088            "assigned"
1089        }
1090        .to_owned()
1091    });
1092    let time = |at: Option<jiff::Timestamp>| at.map_or_else(String::new, |t| show_short(t, local));
1093    vec![
1094        attempt.try_number.to_string(),
1095        status,
1096        attempt.worker_id.clone().unwrap_or_default(),
1097        time(attempt.started_at),
1098        time(attempt.ended_at),
1099        // Measured by the worker; the timestamps are the master's.
1100        attempt.duration_ms.map_or_else(String::new, seconds),
1101        attempt
1102            .exit_code
1103            .map_or_else(String::new, |c| c.to_string()),
1104        attempt_error(attempt),
1105    ]
1106}
1107
1108/// A duration measured in milliseconds, in seconds rounded to a tenth (half up): `0.1s` for
1109/// 99 ms, `0.3s` for 250 ms. `tasks attempts` and `dags test` both show it so.
1110pub(crate) fn seconds(ms: u64) -> String {
1111    let tenths = (ms + 50) / 100;
1112    format!("{}.{}s", tenths / 10, tenths % 10)
1113}
1114
1115/// What went wrong, in a cell: the error kind schedr recognised, else the task's own
1116/// exception and the first line of its message (the whole summary is in `--json`).
1117fn attempt_error(attempt: &AttemptView) -> String {
1118    const WIDTH: usize = 60;
1119    if let Some(kind) = &attempt.error_kind {
1120        return kind.clone();
1121    }
1122    let Some(summary) = &attempt.error_summary else {
1123        return String::new();
1124    };
1125    let exception = summary["exception"].as_str().unwrap_or_default();
1126    let message = summary["message"]
1127        .as_str()
1128        .and_then(|m| m.lines().next())
1129        .unwrap_or_default();
1130    let text = match (exception.is_empty(), message.is_empty()) {
1131        (false, false) => format!("{exception}: {message}"),
1132        (false, true) => exception.to_owned(),
1133        _ => message.to_owned(),
1134    };
1135    if text.chars().count() <= WIDTH {
1136        return text;
1137    }
1138    let cut: String = text.chars().take(WIDTH - 1).collect();
1139    format!("{cut}…")
1140}
1141
1142/// A task as shown: `fetch`, or `fetch[2]` for an instance of a mapped task (decision 86).
1143fn shown_task(task_id: &str, map_index: Option<u32>) -> String {
1144    map_index.map_or_else(|| task_id.to_owned(), |i| format!("{task_id}[{i}]"))
1145}
1146
1147/// A `--for`-style time, its warning (an offset-free time read as UTC) written to `err`.
1148pub(crate) fn for_time(
1149    text: Option<&str>,
1150    err: &mut impl Write,
1151) -> Result<Option<jiff::Timestamp>, AppError> {
1152    let Some(text) = text else {
1153        return Ok(None);
1154    };
1155    let parsed = parse_for(text).map_err(AppError::BadArgument)?;
1156    if let Some(warning) = parsed.warning {
1157        writeln!(err, "{warning}")?;
1158    }
1159    Ok(Some(parsed.at))
1160}
1161
1162fn done(
1163    out: &mut impl Write,
1164    output: &Output,
1165    command: &CommandView,
1166    message: &str,
1167) -> Result<(), AppError> {
1168    if output.json {
1169        return print_json(out, command);
1170    }
1171    writeln!(out, "{message}")?;
1172    Ok(())
1173}
1174
1175fn print_json(out: &mut impl Write, value: &impl serde::Serialize) -> Result<(), AppError> {
1176    let text =
1177        serde_json::to_string_pretty(value).map_err(|e| AppError::BadArgument(e.to_string()))?;
1178    writeln!(out, "{text}")?;
1179    Ok(())
1180}
1181
1182/// A run's parameters from `-p` fields (`key=value` a text, `key:=json` any JSON value, the
1183/// field syntax of the in-task CLI) or `--params` (one JSON object); `None` when none given.
1184///
1185/// # Errors
1186///
1187/// [`AppError::BadArgument`] for a field without `=`, an empty or repeated name, JSON that
1188/// doesn't read, or `--params` that isn't an object.
1189pub fn given_params(
1190    fields: &[String],
1191    json: Option<&str>,
1192) -> Result<Option<serde_json::Map<String, serde_json::Value>>, AppError> {
1193    if let Some(json) = json {
1194        return match serde_json::from_str(json) {
1195            Ok(serde_json::Value::Object(params)) => Ok(Some(params)),
1196            Ok(_) => Err(AppError::BadArgument(
1197                "--params takes a JSON object, e.g. '{\"region\": \"us\"}'".to_owned(),
1198            )),
1199            Err(e) => Err(AppError::BadArgument(format!("--params isn't JSON: {e}"))),
1200        };
1201    }
1202    if fields.is_empty() {
1203        return Ok(None);
1204    }
1205    // A refusal names the field by its number, or by its name masked, never by its value: it
1206    // may be a secret, mistyped.
1207    let mut params = serde_json::Map::new();
1208    for (n, field) in fields.iter().enumerate().map(|(i, f)| (i + 1, f)) {
1209        let Some((name, value)) = field.split_once('=') else {
1210            return Err(AppError::BadArgument(format!(
1211                "-p #{n}: give `name=text` or `name:=json`"
1212            )));
1213        };
1214        let json_name = name.strip_suffix(':');
1215        let name = json_name.unwrap_or(name);
1216        if name.is_empty() {
1217            return Err(AppError::BadArgument(format!(
1218                "-p #{n}: no name before `=`"
1219            )));
1220        }
1221        let value = match json_name {
1222            Some(_) => serde_json::from_str(value).map_err(|e| {
1223                AppError::BadArgument(format!(
1224                    "-p {}: the value isn't JSON (line {}, column {}); text is `name=...`",
1225                    schedr_config::masked::mask_text(name),
1226                    e.line(),
1227                    e.column()
1228                ))
1229            })?,
1230            None => serde_json::Value::String(value.to_owned()),
1231        };
1232        if params.insert(name.to_owned(), value).is_some() {
1233            return Err(AppError::BadArgument(format!(
1234                "-p: `{}` is given twice",
1235                schedr_config::masked::mask_text(name)
1236            )));
1237        }
1238    }
1239    Ok(Some(params))
1240}
1241
1242fn dag_rows(dags: &[DagView], local: &TimeZone) -> Vec<Vec<String>> {
1243    dags.iter()
1244        .map(|dag| {
1245            let place = dag.conflict.as_ref().map_or_else(
1246                || {
1247                    dag.location
1248                        .as_ref()
1249                        .map_or_else(String::new, |l| format!("{}:{}", l.root, l.path))
1250                },
1251                |places| format!("CONFLICT: {} places", places.len()),
1252            );
1253            vec![
1254                dag.dag_id.clone(),
1255                TriggerState::shown(dag.trigger_state).to_owned(),
1256                // Held while its file fails to import (decision 72): the error's class (the
1257                // message is on the UI's Import errors page).
1258                dag.held
1259                    .as_ref()
1260                    .map_or_else(|| "no".to_owned(), |h| format!("yes: {}", h.exception)),
1261                dag.trigger
1262                    .as_ref()
1263                    .map_or_else(String::new, |t| trigger_text(t, local)),
1264                place,
1265            ]
1266        })
1267        .collect()
1268}
1269
1270/// A run's state, with why a `success` turned yellow after its end (decision 309):
1271/// `success (late_cleanup_failed)`.
1272fn run_state(run: &RunView) -> String {
1273    match &run.late_failure {
1274        Some(late) => format!("{} ({late})", run.state),
1275        None => run.state.clone(),
1276    }
1277}
1278
1279fn run_row(run: &RunView, local: &TimeZone) -> Vec<String> {
1280    vec![
1281        run.run_id.clone(),
1282        run.kind_label(),
1283        run_state(run),
1284        show(run.planned_for, local),
1285        run.triggered_by.clone(),
1286    ]
1287}
1288
1289/// Writes rows under headers in aligned columns (two spaces apart); no trailing spaces.
1290pub(crate) fn write_table(
1291    out: &mut impl Write,
1292    headers: &[&str],
1293    rows: &[Vec<String>],
1294) -> Result<(), AppError> {
1295    let mut widths: Vec<usize> = headers.iter().map(|h| h.chars().count()).collect();
1296    for row in rows {
1297        for (width, cell) in widths.iter_mut().zip(row) {
1298            *width = (*width).max(cell.chars().count());
1299        }
1300    }
1301    let line = |cells: Vec<&str>| -> String {
1302        let mut text = String::new();
1303        for (i, (cell, width)) in cells.iter().zip(&widths).enumerate() {
1304            if i > 0 {
1305                text.push_str("  ");
1306            }
1307            text.push_str(cell);
1308            if i + 1 < cells.len() {
1309                text.push_str(&" ".repeat(width - cell.chars().count()));
1310            }
1311        }
1312        // Empty cells at the end of a row leave no padding behind.
1313        text.truncate(text.trim_end().len());
1314        text
1315    };
1316    writeln!(out, "{}", line(headers.to_vec()))?;
1317    for row in rows {
1318        writeln!(out, "{}", line(row.iter().map(String::as_str).collect()))?;
1319    }
1320    Ok(())
1321}