Skip to main content

runnerd_core/api/
actions.rs

1//! Cancelling a job's run and re-running a job on GitHub (ADR 0134): the routes' query, the preview a request gets
2//! before anything is sent, GitHub's answer and every sentence clients show of them. Plain data and wording;
3//! `runnerd_core::actions` decides, issues the confirmations and sends. Nothing here holds GitHub's own text: a
4//! refusal is its class and HTTP status, and every name a preview shows is cleaned of control characters and escapes
5//! before it reaches a client.
6
7use serde::{Deserialize, Serialize};
8
9use super::{JobSummary, Tone, duration};
10
11/// The doctor check that says whether the token can cancel and re-run jobs. Advisory: the attention list leaves it
12/// out whatever its status, since only GitHub's answer to a real request says for sure.
13pub const JOB_ACTIONS_CHECK: &str = "job actions";
14
15/// The most other jobs of the run a confirmation names.
16pub const SIBLINGS_MAX: usize = 50;
17
18/// The longest job name a sentence quotes, in characters.
19const NAME_MAX: usize = 80;
20
21/// How long a preview's confirmation can be sent back, in seconds.
22pub const CONFIRM_SECS: u64 = 300;
23
24/// What an owner asks GitHub to do with a job.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
26#[serde(rename_all = "kebab-case")]
27pub enum JobAction {
28    /// Cancel the job's workflow run: GitHub cancels runs, not single jobs.
29    Cancel,
30    /// Re-run the job, and with it the jobs that depend on it.
31    Rerun,
32    /// Re-run the failed jobs of the job's run, and the jobs that depend on them.
33    RerunFailed,
34    /// An action a newer daemon knows and this client does not.
35    #[serde(other)]
36    Unsupported,
37}
38
39impl JobAction {
40    /// The actions a client offers on `job` as it stands: cancel while it is queued or runs, a re-run once it is
41    /// final, and once it failed, a re-run of its run's failed jobs too. GitHub decides the rest; a client offers
42    /// none while `Status::job_actions` is not on ([`JobActions::offered`]).
43    pub fn for_job(job: &JobSummary) -> &'static [JobAction] {
44        if !job.state.is_final() {
45            &[JobAction::Cancel]
46        } else if job.outcome().kind == super::OutcomeKind::Failed {
47            &[JobAction::Rerun, JobAction::RerunFailed]
48        } else {
49            &[JobAction::Rerun]
50        }
51    }
52
53    /// Its name in a log line.
54    pub fn slug(self) -> &'static str {
55        match self {
56            JobAction::Cancel => "cancel",
57            JobAction::Rerun => "rerun",
58            JobAction::RerunFailed => "rerun-failed",
59            JobAction::Unsupported => "unsupported",
60        }
61    }
62
63    /// What a confirming button or prompt says: `Cancel run`, `Re-run job`, `Re-run failed jobs`.
64    pub fn confirm_label(self) -> &'static str {
65        match self {
66            JobAction::Cancel => "Cancel run",
67            JobAction::Rerun => "Re-run job",
68            JobAction::RerunFailed => "Re-run failed jobs",
69            JobAction::Unsupported => "Confirm",
70        }
71    }
72}
73
74/// Whether a daemon cancels and re-runs jobs, as `GET /v1/status` says.
75#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "kebab-case")]
77pub enum JobActions {
78    /// It does.
79    On,
80    /// `[github] job_actions = false`: both routes answer 403.
81    Off,
82    /// A daemon without the routes, before 0.2, or a state this client does not know: never read as on.
83    #[default]
84    #[serde(other)]
85    Unsupported,
86}
87
88impl JobActions {
89    /// From `[github] job_actions`.
90    pub fn configured(on: bool) -> JobActions {
91        if on { JobActions::On } else { JobActions::Off }
92    }
93
94    /// Whether a client may offer cancel and re-run.
95    pub fn offered(self) -> bool {
96        self == JobActions::On
97    }
98
99    /// Why a client offers neither, `None` while it does.
100    pub fn why_not(self) -> Option<&'static str> {
101        match self {
102            JobActions::On => None,
103            JobActions::Off => Some(actions_off()),
104            JobActions::Unsupported => {
105                Some("this runnerd cannot cancel or re-run jobs: it is older than this client")
106            }
107        }
108    }
109}
110
111/// What both routes answer, 403, while `[github] job_actions` is off.
112pub fn actions_off() -> &'static str {
113    "runnerd does not cancel or re-run jobs: [github] job_actions is false in its config"
114}
115
116/// The 403 for a job of a repository the config no longer has.
117pub fn actions_not_configured(repository: &str) -> String {
118    format!(
119        "{repository} is not a configured repository; runnerd cancels and re-runs only the jobs of configured ones"
120    )
121}
122
123/// The 409 while another action on the same run is being sent to GitHub, or one with the same confirmation.
124pub fn actions_in_flight(other: JobAction, run: u64) -> String {
125    let what = match other {
126        JobAction::Cancel => "a cancel",
127        JobAction::Rerun => "a re-run of a job",
128        JobAction::RerunFailed => "a re-run of the failed jobs",
129        JobAction::Unsupported => "another action",
130    };
131    format!("{what} of run {run} is being sent to GitHub; ask again once it answers")
132}
133
134/// The 422 for a job whose run the history did not record.
135pub fn actions_no_run(job: u64) -> String {
136    format!("the history has no workflow run for job {job}, so runnerd cannot ask GitHub about it")
137}
138
139/// `POST /v1/jobs/{id}/cancel` and `POST /v1/jobs/{id}/rerun` query parameters.
140#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
141pub struct ActionQuery {
142    /// Send it. Without it, or without a `confirm` this daemon issued, the answer is a 409 [`ActionPreview`] and
143    /// nothing is sent to GitHub.
144    #[serde(default)]
145    pub force: bool,
146    /// The preview's `confirm`: an opaque token this daemon issued with it, for [`CONFIRM_SECS`], that sends what it
147    /// showed (the action, repository, run, attempt and job, under the config it was shown with) once.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub confirm: Option<String>,
150    /// Re-run the run's failed jobs rather than this job; only for `rerun`.
151    #[serde(default)]
152    pub failed: bool,
153}
154
155/// What an action acts on: the job as the history records it, and the run's attempt as GitHub said it.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct ActionTarget {
158    /// What is asked.
159    pub action: JobAction,
160    /// The job it was asked from.
161    pub job: u64,
162    /// The job's name in its workflow, as GitHub named it.
163    pub name: String,
164    /// `owner/name`.
165    pub repository: String,
166    /// The job's workflow run.
167    pub run: u64,
168    /// The run's current attempt, as GitHub said it; `None` when it could not be read.
169    pub attempt: Option<u32>,
170}
171
172impl ActionTarget {
173    /// `run 4182`, or `run 4182 (attempt 3)` once GitHub said which attempt is current.
174    fn run_words(&self) -> String {
175        match self.attempt {
176            Some(attempt) => format!("run {} (attempt {attempt})", self.run),
177            None => format!("run {}", self.run),
178        }
179    }
180
181    /// The job's name for a sentence: without control characters or escapes, at most `NAME_MAX` characters, `job
182    /// <id>` while unknown.
183    fn name(&self) -> String {
184        let plain = super::jobs::plain(&self.name);
185        let plain = plain.trim();
186        if plain.is_empty() {
187            return format!("job {}", self.job);
188        }
189        if plain.chars().count() > NAME_MAX {
190            let cut: String = plain.chars().take(NAME_MAX - 1).collect();
191            return format!("{cut}…");
192        }
193        plain.to_owned()
194    }
195
196    /// What is asked, in the words of a confirmation's title.
197    fn title(&self) -> String {
198        let (run, repository) = (self.run_words(), &self.repository);
199        match self.action {
200            JobAction::Cancel => format!("Cancel {run} of {repository}?"),
201            JobAction::Rerun => format!("Re-run {} of {repository}?", self.name()),
202            JobAction::RerunFailed => {
203                format!("Re-run the failed jobs of {run} of {repository}?")
204            }
205            JobAction::Unsupported => format!("Act on {run} of {repository}?"),
206        }
207    }
208
209    /// What GitHub does with it, which is more than one job.
210    fn scope(&self) -> String {
211        let run = self.run;
212        match self.action {
213            JobAction::Cancel => "GitHub cancels the whole run, not one job: every job of it still queued or running \
214                                  stops, here and on any other runner."
215                .to_owned(),
216            JobAction::Rerun => format!(
217                "GitHub re-runs this job and the jobs that depend on it, in a new attempt of run {run}."
218            ),
219            JobAction::RerunFailed => format!(
220                "GitHub re-runs the failed jobs of run {run} and the jobs that depend on them, in a new attempt."
221            ),
222            JobAction::Unsupported => String::new(),
223        }
224    }
225}
226
227/// The 409 a request without `force`, or with a `confirm` for something else, gets: what the action would do, said
228/// before anything is sent to GitHub. Has the `message` of an [`ErrorResponse`](super::ErrorResponse), so a client
229/// that reads only that still gets it.
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231pub struct ActionPreview {
232    /// The title and the scope in one line.
233    pub message: String,
234    /// What would be asked.
235    pub action: JobAction,
236    /// The job it is asked from.
237    pub job: u64,
238    /// `owner/name`.
239    pub repository: String,
240    /// The job's workflow run.
241    pub run: u64,
242    /// The run's current attempt as GitHub said it, which a confirmation acts on; `None` when it could not be read,
243    /// and then there is no `confirm`.
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub attempt: Option<u32>,
246    /// `Cancel run 4182 (attempt 3) of halyard/ledger?`
247    pub title: String,
248    /// What GitHub does, which is more than one job.
249    pub scope: String,
250    /// What else holds now: why an earlier confirmation was not taken, the run could not be read, it completed, the
251    /// job is of an earlier attempt, the repository is paused. Often none.
252    #[serde(default)]
253    pub notes: Vec<String>,
254    /// Other jobs of the run the history has, newest attempt first, at most [`SIBLINGS_MAX`], their names, workflows
255    /// and branches cleaned of control characters and escapes. GitHub may have more: jobs on other runners, and jobs
256    /// not queued yet.
257    #[serde(default)]
258    pub siblings: Vec<JobSummary>,
259    /// What `siblings` covers, never "all of them".
260    pub siblings_note: String,
261    /// What the confirming button or prompt says.
262    pub confirm_label: String,
263    /// Send it back as `confirm` with `force=true` to act, within [`CONFIRM_SECS`] and once. `None` when nothing
264    /// can be sent: the run could not be read, so what a confirmation would act on is unknown.
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub confirm: Option<String>,
267}
268
269/// The run as GitHub said it when the preview was made.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub enum RunSeen {
272    /// Read: its current attempt, and whether it completed.
273    Now {
274        /// The current attempt.
275        attempt: u32,
276        /// Whether it completed.
277        completed: bool,
278    },
279    /// Not read: GitHub answered `status`, or did not answer.
280    Unread {
281        /// The HTTP status, when GitHub answered.
282        status: Option<u16>,
283    },
284}
285
286/// Why a request that came with a confirmation got a new preview instead, and nothing was sent.
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub enum Superseded {
289    /// This runnerd holds no such confirmation: it ran out, runnerd restarted since, or another runnerd issued it.
290    Unknown,
291    /// It was sent already.
292    Used,
293    /// It was issued for another action or job.
294    OtherRequest,
295    /// The config's job actions or repositories changed since it was issued.
296    ConfigChanged,
297    /// The run moved to another attempt since it was issued.
298    AttemptChanged,
299    /// The run could not be read again right before the send.
300    Unverified,
301}
302
303/// The facts of an [`ActionPreview`]: what the route found for the job.
304#[derive(Debug, Clone)]
305pub struct PreviewFacts {
306    /// What is asked of which job; its `attempt` is `run`'s, when read.
307    pub target: ActionTarget,
308    /// The attempt of the run the job ran in, as the history says.
309    pub job_attempt: u32,
310    /// The run as GitHub said it.
311    pub run: RunSeen,
312    /// Why the request's confirmation was not taken, if it came with one.
313    pub superseded: Option<Superseded>,
314    /// The confirmation issued with this preview; `None` when the run was not read.
315    pub confirm: Option<String>,
316    /// Whether the repository is paused.
317    pub paused: bool,
318    /// The other jobs of the run the history has, newest attempt first, at most [`SIBLINGS_MAX`].
319    pub siblings: Vec<JobSummary>,
320    /// Whether the history has more of them than `siblings`.
321    pub more: bool,
322}
323
324impl ActionPreview {
325    /// The preview core words for `facts`.
326    pub fn new(facts: PreviewFacts) -> ActionPreview {
327        let PreviewFacts {
328            mut target,
329            job_attempt,
330            run,
331            superseded,
332            confirm,
333            paused,
334            siblings,
335            more,
336        } = facts;
337        let mut notes = Vec::new();
338        if let Some(superseded) = superseded {
339            notes.push(superseded_note(superseded));
340        }
341        let rerun = matches!(target.action, JobAction::Rerun | JobAction::RerunFailed);
342        match run {
343            RunSeen::Now { attempt, completed } => {
344                target.attempt = Some(attempt);
345                if completed && target.action == JobAction::Cancel {
346                    notes.push(format!(
347                        "Run {} has completed: GitHub has nothing left to cancel.",
348                        target.run
349                    ));
350                }
351                if !completed && rerun {
352                    notes.push(format!(
353                        "Run {} has not completed; GitHub refuses to re-run a run that has not.",
354                        target.run
355                    ));
356                }
357                if job_attempt < attempt {
358                    notes.push(match target.action {
359                        JobAction::Cancel => format!(
360                            "This job ran in attempt {job_attempt}; the cancel stops attempt {attempt}, the run's \
361                             current one."
362                        ),
363                        _ => format!("This job ran in attempt {job_attempt}; the run is at attempt {attempt} now."),
364                    });
365                }
366            }
367            RunSeen::Unread { status } => {
368                target.attempt = None;
369                let answered = status.map_or_else(
370                    || "it did not answer".to_owned(),
371                    |status| format!("it answered {status}"),
372                );
373                notes.push(format!(
374                    "runnerd could not read run {} from GitHub ({answered}), so it cannot say which attempt this \
375                     would act on, and offers no confirmation. Ask again later.",
376                    target.run
377                ));
378            }
379        }
380        if paused && rerun {
381            notes.push(format!(
382                "{} is paused: runnerd starts none of the new attempt's jobs until it is resumed; other runners \
383                 may take them.",
384                target.repository
385            ));
386        }
387        let siblings_note = match (siblings.len(), more) {
388            (0, _) => {
389                "runnerd knows no other job of this run; GitHub may have some, on other runners."
390                    .to_owned()
391            }
392            (1, false) => {
393                "runnerd knows 1 other job of this run; GitHub may have more, on other runners."
394                    .to_owned()
395            }
396            (count, false) => format!(
397                "runnerd knows {count} other jobs of this run; GitHub may have more, on other runners."
398            ),
399            (count, true) => format!(
400                "runnerd knows more than {count} other jobs of this run, the first {count} shown; GitHub may have \
401                 more still."
402            ),
403        };
404        let title = target.title();
405        let scope = target.scope();
406        ActionPreview {
407            message: format!("{title} {scope}"),
408            action: target.action,
409            job: target.job,
410            repository: target.repository.clone(),
411            run: target.run,
412            attempt: target.attempt,
413            title,
414            scope,
415            notes,
416            siblings: siblings.into_iter().map(cleaned).collect(),
417            siblings_note,
418            confirm_label: target.action.confirm_label().to_owned(),
419            confirm,
420        }
421    }
422}
423
424/// Why a confirmation was not taken, in words.
425fn superseded_note(superseded: Superseded) -> String {
426    let minutes = CONFIRM_SECS / 60;
427    match superseded {
428        Superseded::Unknown => format!(
429            "That confirmation is not one this runnerd holds: it lasts {minutes} minutes, and a restart forgets it. \
430             Nothing was sent; this is a new preview."
431        ),
432        Superseded::Used => {
433            "That confirmation was sent already, and is sent once. Nothing more was sent; this is a new preview."
434                .to_owned()
435        }
436        Superseded::OtherRequest => "That confirmation is for another action or job. Nothing was sent; this is a \
437                                     new preview."
438            .to_owned(),
439        Superseded::ConfigChanged => "runnerd's config changed what it may do since that confirmation. Nothing was \
440                                      sent; this is a new preview."
441            .to_owned(),
442        Superseded::AttemptChanged => "The run moved to another attempt since that confirmation. Nothing was sent; \
443                                       this is a new preview of the attempt it is at now."
444            .to_owned(),
445        Superseded::Unverified => "runnerd could not read the run again right before sending, so it sent nothing; \
446                                   this is a new preview."
447            .to_owned(),
448    }
449}
450
451/// A sibling as a preview shows it: every text GitHub named cleaned of control characters and escapes. The history
452/// keeps the original.
453fn cleaned(job: JobSummary) -> JobSummary {
454    let clean = |text: &String| super::jobs::plain(text);
455    JobSummary {
456        name: clean(&job.name),
457        repository: clean(&job.repository),
458        workflow: job.workflow.as_ref().map(clean),
459        branch: job.branch.as_ref().map(clean),
460        conclusion: job.conclusion.as_ref().map(clean),
461        url: job.url.as_ref().map(clean),
462        labels: job.labels.iter().map(clean).collect(),
463        runner: job.runner.as_ref().map(|runner| super::JobRunner {
464            name: clean(&runner.name),
465            ..runner.clone()
466        }),
467        ..job
468    }
469}
470
471/// How GitHub took an action.
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
473#[serde(rename_all = "kebab-case")]
474pub enum ActionOutcome {
475    /// GitHub accepted it. It answers with an acknowledgement: a cancel takes effect as the runners report it, a
476    /// re-run's new jobs show up as they queue.
477    Accepted,
478    /// The run had finished already: GitHub answered 409 and a read of the run said it completed.
479    AlreadyFinished,
480    /// GitHub, or runnerd before sending, refused it: nothing was done.
481    Refused,
482    /// runnerd cannot tell whether GitHub did it: the request may have reached GitHub and its answer not come back.
483    /// Also how this client reads an outcome only a newer daemon knows.
484    #[serde(other)]
485    Unknown,
486}
487
488/// What class of refusal an [`ActionOutcome::Refused`] was. Never GitHub's own words.
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
490#[serde(rename_all = "kebab-case")]
491pub enum ActionRefusal {
492    /// runnerd could read no GitHub token: nothing was sent.
493    NoToken,
494    /// runnerd could not reach GitHub: nothing was sent.
495    Unreachable,
496    /// GitHub refused the token: 401.
497    Unauthorized,
498    /// 403: the token lacks the permission, or GitHub does not allow the action for the run now.
499    Forbidden,
500    /// 404 or 410: GitHub does not show the run or the job to this token, or it is gone.
501    NotFound,
502    /// 409: the run's state does not allow it, for a cancel while the run had not completed.
503    Conflict,
504    /// 422: GitHub cannot do it for this run.
505    Unprocessable,
506    /// GitHub's rate limit is used up: nothing was sent, or GitHub refused for it.
507    RateLimited,
508    /// Another error status below 500, such as a 400.
509    Failed,
510    /// runnerd's config changed between the confirmation and the request (job actions turned off, the repositories
511    /// changed): runnerd sent nothing.
512    Withdrawn,
513    /// A class only a newer daemon knows.
514    #[serde(other)]
515    Other,
516}
517
518/// Why runnerd cannot tell what GitHub did. Not on the wire: the result's `message` words it.
519#[derive(Debug, Clone, Copy, PartialEq, Eq)]
520pub enum UnknownCause {
521    /// No answer within the request's deadline.
522    TimedOut,
523    /// The connection broke after the request may have been sent.
524    Broken,
525    /// GitHub, or a gateway in front of it, answered with a server error (5xx): it may have done it.
526    ServerError,
527    /// runnerd began to stop while GitHub was asked.
528    Stopping,
529}
530
531/// What GitHub answered an action, as runnerd classifies it.
532#[derive(Debug, Clone, Copy, PartialEq, Eq)]
533pub enum ActionAnswer {
534    /// A 2xx.
535    Accepted {
536        /// Its HTTP status.
537        status: u16,
538    },
539    /// A cancel's 409, with a read of the run that said it completed.
540    AlreadyFinished {
541        /// Its HTTP status.
542        status: u16,
543    },
544    /// Refused, with nothing done.
545    Refused {
546        /// Its class.
547        refusal: ActionRefusal,
548        /// The HTTP status, when GitHub answered.
549        status: Option<u16>,
550        /// For a rate limit, when it resets, in seconds since the Unix epoch.
551        until: Option<u64>,
552    },
553    /// Whether GitHub did it is unknown.
554    Unknown {
555        /// Why.
556        cause: UnknownCause,
557        /// The HTTP status, when one came.
558        status: Option<u16>,
559    },
560}
561
562/// `POST /v1/jobs/{id}/cancel` and `POST /v1/jobs/{id}/rerun` once GitHub was asked: how it took it. The job's record
563/// is not changed: GitHub's listings bring the run's new state and a re-run's new jobs.
564#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
565pub struct ActionResult {
566    /// What was asked.
567    pub action: JobAction,
568    /// The job it was asked from.
569    pub job: u64,
570    /// `owner/name`.
571    pub repository: String,
572    /// The job's workflow run.
573    pub run: u64,
574    /// How GitHub took it.
575    pub outcome: ActionOutcome,
576    /// GitHub's HTTP status, when it answered.
577    #[serde(default, skip_serializing_if = "Option::is_none")]
578    pub status: Option<u16>,
579    /// For a refusal, its class.
580    #[serde(default, skip_serializing_if = "Option::is_none")]
581    pub refusal: Option<ActionRefusal>,
582    /// For a rate limit, when it resets, in seconds since the Unix epoch.
583    #[serde(default, skip_serializing_if = "Option::is_none")]
584    pub until: Option<u64>,
585    /// What happened, in words.
586    pub message: String,
587}
588
589impl ActionResult {
590    /// The result core words for `answer` to `target`, at `now`.
591    pub fn new(target: &ActionTarget, answer: ActionAnswer, now: u64) -> ActionResult {
592        let (outcome, status, refusal, until) = match answer {
593            ActionAnswer::Accepted { status } => {
594                (ActionOutcome::Accepted, Some(status), None, None)
595            }
596            ActionAnswer::AlreadyFinished { status } => {
597                (ActionOutcome::AlreadyFinished, Some(status), None, None)
598            }
599            ActionAnswer::Refused {
600                refusal,
601                status,
602                until,
603            } => (ActionOutcome::Refused, status, Some(refusal), until),
604            ActionAnswer::Unknown { status, .. } => (ActionOutcome::Unknown, status, None, None),
605        };
606        let message = match answer {
607            ActionAnswer::Accepted { .. } => accepted(target),
608            ActionAnswer::AlreadyFinished { .. } => format!(
609                "Run {} of {} had completed already: nothing was cancelled.",
610                target.run, target.repository
611            ),
612            ActionAnswer::Refused {
613                refusal,
614                status,
615                until,
616            } => refused(target, refusal, status, until, now),
617            ActionAnswer::Unknown { cause, status } => unknown(target, cause, status),
618        };
619        ActionResult {
620            action: target.action,
621            job: target.job,
622            repository: target.repository.clone(),
623            run: target.run,
624            outcome,
625            status,
626            refusal,
627            until,
628            message,
629        }
630    }
631
632    /// What it means for the reader.
633    pub fn tone(&self) -> Tone {
634        match self.outcome {
635            ActionOutcome::Accepted => Tone::Good,
636            ActionOutcome::AlreadyFinished => Tone::Neutral,
637            ActionOutcome::Refused => Tone::Bad,
638            ActionOutcome::Unknown => Tone::Warn,
639        }
640    }
641
642    /// Whether GitHub took it, or there was nothing to do: what a command's exit status says.
643    pub fn succeeded(&self) -> bool {
644        matches!(
645            self.outcome,
646            ActionOutcome::Accepted | ActionOutcome::AlreadyFinished
647        )
648    }
649}
650
651fn accepted(target: &ActionTarget) -> String {
652    let (run, repository) = (target.run_words(), &target.repository);
653    match target.action {
654        JobAction::Cancel => format!(
655            "GitHub is cancelling {run} of {repository}; its jobs end as their runners report it."
656        ),
657        JobAction::Rerun => format!(
658            "GitHub re-runs {} and the jobs that depend on it in a new attempt of {run}; they show here as \
659             they queue.",
660            target.name()
661        ),
662        JobAction::RerunFailed => format!(
663            "GitHub re-runs the failed jobs of {run} and the jobs that depend on them in a new attempt; they \
664             show here as they queue."
665        ),
666        JobAction::Unsupported => format!("GitHub accepted the action on {run}."),
667    }
668}
669
670/// What was refused, before why.
671fn asked(target: &ActionTarget) -> String {
672    match target.action {
673        JobAction::Cancel => format!("cancel {}", target.run_words()),
674        JobAction::Rerun => format!("re-run {}", target.name()),
675        JobAction::RerunFailed => format!("re-run the failed jobs of {}", target.run_words()),
676        JobAction::Unsupported => format!("act on {}", target.run_words()),
677    }
678}
679
680fn refused(
681    target: &ActionTarget,
682    refusal: ActionRefusal,
683    status: Option<u16>,
684    until: Option<u64>,
685    now: u64,
686) -> String {
687    let asked = asked(target);
688    let repository = &target.repository;
689    let rerun = matches!(target.action, JobAction::Rerun | JobAction::RerunFailed);
690    let why = match refusal {
691        ActionRefusal::NoToken => {
692            return format!("runnerd could read no GitHub token, so it did not {asked}.");
693        }
694        ActionRefusal::Unreachable => {
695            return format!("runnerd could not reach GitHub, so it did not {asked}.");
696        }
697        ActionRefusal::RateLimited => {
698            let wait = until.map_or_else(String::new, |until| {
699                format!(
700                    "; try again in {}",
701                    duration(until.saturating_sub(now).max(1))
702                )
703            });
704            return match status {
705                Some(status) => format!(
706                    "GitHub refused to {asked} ({status}): its rate limit is used up{wait}. Nothing was done."
707                ),
708                None => {
709                    format!("GitHub's rate limit is used up, so runnerd did not {asked}{wait}.")
710                }
711            };
712        }
713        ActionRefusal::Withdrawn => {
714            return format!(
715                "runnerd did not {asked}: its config changed before the request went out (job actions turned off, \
716                 or the repositories changed). Nothing was sent."
717            );
718        }
719        ActionRefusal::Unauthorized => "it refused the token".to_owned(),
720        ActionRefusal::Forbidden if rerun => format!(
721            "the token may lack Actions: write (or the repo scope) on {repository}, or the run has not finished"
722        ),
723        ActionRefusal::Forbidden => {
724            format!("the token may lack Actions: write (or the repo scope) on {repository}")
725        }
726        ActionRefusal::NotFound => {
727            "it does not show the run to this token, or the run is gone".to_owned()
728        }
729        ActionRefusal::Conflict => "the run's state does not allow it now".to_owned(),
730        ActionRefusal::Unprocessable => "it cannot do that for this run".to_owned(),
731        ActionRefusal::Failed | ActionRefusal::Other => "it failed".to_owned(),
732    };
733    let status = status.map_or_else(String::new, |status| format!(" ({status})"));
734    format!("GitHub refused to {asked}{status}: {why}. Nothing was done.")
735}
736
737fn unknown(target: &ActionTarget, cause: UnknownCause, status: Option<u16>) -> String {
738    let why = match cause {
739        UnknownCause::TimedOut => "GitHub did not answer in time".to_owned(),
740        UnknownCause::Broken => "the connection broke after the request went out".to_owned(),
741        UnknownCause::ServerError => match status {
742            Some(status) => format!(
743                "GitHub answered {status}, a server error, which does not say whether it acted"
744            ),
745            None => "GitHub answered with a server error, which does not say whether it acted"
746                .to_owned(),
747        },
748        UnknownCause::Stopping => "runnerd began to stop while GitHub was asked".to_owned(),
749    };
750    let asked = asked(target);
751    format!(
752        "runnerd cannot tell whether GitHub did {asked}: {why}. Check the run on GitHub before asking again."
753    )
754}
755
756#[cfg(all(test, any(feature = "host", feature = "client")))]
757mod tests;