1use serde::{Deserialize, Serialize};
8
9use super::{JobSummary, Tone, duration};
10
11pub const JOB_ACTIONS_CHECK: &str = "job actions";
14
15pub const SIBLINGS_MAX: usize = 50;
17
18const NAME_MAX: usize = 80;
20
21pub const CONFIRM_SECS: u64 = 300;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
26#[serde(rename_all = "kebab-case")]
27pub enum JobAction {
28 Cancel,
30 Rerun,
32 RerunFailed,
34 #[serde(other)]
36 Unsupported,
37}
38
39impl JobAction {
40 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 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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "kebab-case")]
77pub enum JobActions {
78 On,
80 Off,
82 #[default]
84 #[serde(other)]
85 Unsupported,
86}
87
88impl JobActions {
89 pub fn configured(on: bool) -> JobActions {
91 if on { JobActions::On } else { JobActions::Off }
92 }
93
94 pub fn offered(self) -> bool {
96 self == JobActions::On
97 }
98
99 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
111pub fn actions_off() -> &'static str {
113 "runnerd does not cancel or re-run jobs: [github] job_actions is false in its config"
114}
115
116pub 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
123pub 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
134pub 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
141pub struct ActionQuery {
142 #[serde(default)]
145 pub force: bool,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub confirm: Option<String>,
150 #[serde(default)]
152 pub failed: bool,
153}
154
155#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct ActionTarget {
158 pub action: JobAction,
160 pub job: u64,
162 pub name: String,
164 pub repository: String,
166 pub run: u64,
168 pub attempt: Option<u32>,
170}
171
172impl ActionTarget {
173 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231pub struct ActionPreview {
232 pub message: String,
234 pub action: JobAction,
236 pub job: u64,
238 pub repository: String,
240 pub run: u64,
242 #[serde(default, skip_serializing_if = "Option::is_none")]
245 pub attempt: Option<u32>,
246 pub title: String,
248 pub scope: String,
250 #[serde(default)]
253 pub notes: Vec<String>,
254 #[serde(default)]
258 pub siblings: Vec<JobSummary>,
259 pub siblings_note: String,
261 pub confirm_label: String,
263 #[serde(default, skip_serializing_if = "Option::is_none")]
266 pub confirm: Option<String>,
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub enum RunSeen {
272 Now {
274 attempt: u32,
276 completed: bool,
278 },
279 Unread {
281 status: Option<u16>,
283 },
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub enum Superseded {
289 Unknown,
291 Used,
293 OtherRequest,
295 ConfigChanged,
297 AttemptChanged,
299 Unverified,
301}
302
303#[derive(Debug, Clone)]
305pub struct PreviewFacts {
306 pub target: ActionTarget,
308 pub job_attempt: u32,
310 pub run: RunSeen,
312 pub superseded: Option<Superseded>,
314 pub confirm: Option<String>,
316 pub paused: bool,
318 pub siblings: Vec<JobSummary>,
320 pub more: bool,
322}
323
324impl ActionPreview {
325 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
424fn 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
451fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
473#[serde(rename_all = "kebab-case")]
474pub enum ActionOutcome {
475 Accepted,
478 AlreadyFinished,
480 Refused,
482 #[serde(other)]
485 Unknown,
486}
487
488#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
490#[serde(rename_all = "kebab-case")]
491pub enum ActionRefusal {
492 NoToken,
494 Unreachable,
496 Unauthorized,
498 Forbidden,
500 NotFound,
502 Conflict,
504 Unprocessable,
506 RateLimited,
508 Failed,
510 Withdrawn,
513 #[serde(other)]
515 Other,
516}
517
518#[derive(Debug, Clone, Copy, PartialEq, Eq)]
520pub enum UnknownCause {
521 TimedOut,
523 Broken,
525 ServerError,
527 Stopping,
529}
530
531#[derive(Debug, Clone, Copy, PartialEq, Eq)]
533pub enum ActionAnswer {
534 Accepted {
536 status: u16,
538 },
539 AlreadyFinished {
541 status: u16,
543 },
544 Refused {
546 refusal: ActionRefusal,
548 status: Option<u16>,
550 until: Option<u64>,
552 },
553 Unknown {
555 cause: UnknownCause,
557 status: Option<u16>,
559 },
560}
561
562#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
565pub struct ActionResult {
566 pub action: JobAction,
568 pub job: u64,
570 pub repository: String,
572 pub run: u64,
574 pub outcome: ActionOutcome,
576 #[serde(default, skip_serializing_if = "Option::is_none")]
578 pub status: Option<u16>,
579 #[serde(default, skip_serializing_if = "Option::is_none")]
581 pub refusal: Option<ActionRefusal>,
582 #[serde(default, skip_serializing_if = "Option::is_none")]
584 pub until: Option<u64>,
585 pub message: String,
587}
588
589impl ActionResult {
590 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 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 pub fn succeeded(&self) -> bool {
644 matches!(
645 self.outcome,
646 ActionOutcome::Accepted | ActionOutcome::AlreadyFinished
647 )
648 }
649}
650
651#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
656pub struct RerunRefused {
657 pub run: u64,
659 pub since: u64,
661 pub refusal: ActionRefusal,
663 #[serde(default, skip_serializing_if = "Option::is_none")]
665 pub status: Option<u16>,
666 pub message: String,
668}
669
670impl RerunRefused {
671 pub fn new(result: &ActionResult, now: u64) -> RerunRefused {
673 RerunRefused {
674 run: result.run,
675 since: now,
676 refusal: result.refusal.unwrap_or(ActionRefusal::Other),
677 status: result.status,
678 message: result.message.clone(),
679 }
680 }
681
682 pub fn unread(repository: &str, run: u64, answer: ActionAnswer, now: u64) -> RerunRefused {
685 let (refusal, status) = match answer {
686 ActionAnswer::Refused {
687 refusal, status, ..
688 } => (refusal, status),
689 ActionAnswer::Accepted { status } | ActionAnswer::AlreadyFinished { status } => {
690 (ActionRefusal::Other, Some(status))
691 }
692 ActionAnswer::Unknown { status, .. } => (ActionRefusal::Other, status),
693 };
694 let code = status.map_or_else(String::new, |status| format!(" ({status})"));
695 let message = match refusal {
696 ActionRefusal::NoToken => format!(
697 "runnerd could read no GitHub token, so it could not read run {run} of {repository}. Nothing was \
698 sent."
699 ),
700 ActionRefusal::Unauthorized => format!(
701 "GitHub refused runnerd's token{code} when it read run {run} of {repository}. Nothing was sent."
702 ),
703 _ => format!(
704 "GitHub would not show run {run} of {repository} to runnerd{code}: the token may lack Actions: read \
705 on it, or the run is gone. Nothing was sent."
706 ),
707 };
708 RerunRefused {
709 run,
710 since: now,
711 refusal,
712 status,
713 message,
714 }
715 }
716
717 pub fn title(&self, repository: &str) -> String {
720 format!(
721 "runnerd holds the re-runs of {repository}'s runner faults for an hour: {}",
722 self.message
723 )
724 }
725
726 pub fn fix(&self) -> &'static str {
728 match self.refusal {
729 ActionRefusal::NoToken | ActionRefusal::Unauthorized => {
730 "Give runnerd a GitHub token it can use; it tries again when the hour is up"
731 }
732 _ => {
733 "Give runnerd's token Actions: write on the repository (the repo scope for a classic token); it tries \
734 again when the hour is up. Or set rerun_runner_faults = false"
735 }
736 }
737 }
738}
739
740fn accepted(target: &ActionTarget) -> String {
741 let (run, repository) = (target.run_words(), &target.repository);
742 match target.action {
743 JobAction::Cancel => format!(
744 "GitHub is cancelling {run} of {repository}; its jobs end as their runners report it."
745 ),
746 JobAction::Rerun => format!(
747 "GitHub re-runs {} and the jobs that depend on it in a new attempt of {run}; they show here as \
748 they queue.",
749 target.name()
750 ),
751 JobAction::RerunFailed => format!(
752 "GitHub re-runs the failed jobs of {run} and the jobs that depend on them in a new attempt; they \
753 show here as they queue."
754 ),
755 JobAction::Unsupported => format!("GitHub accepted the action on {run}."),
756 }
757}
758
759fn asked(target: &ActionTarget) -> String {
761 match target.action {
762 JobAction::Cancel => format!("cancel {}", target.run_words()),
763 JobAction::Rerun => format!("re-run {}", target.name()),
764 JobAction::RerunFailed => format!("re-run the failed jobs of {}", target.run_words()),
765 JobAction::Unsupported => format!("act on {}", target.run_words()),
766 }
767}
768
769fn refused(
770 target: &ActionTarget,
771 refusal: ActionRefusal,
772 status: Option<u16>,
773 until: Option<u64>,
774 now: u64,
775) -> String {
776 let asked = asked(target);
777 let repository = &target.repository;
778 let rerun = matches!(target.action, JobAction::Rerun | JobAction::RerunFailed);
779 let why = match refusal {
780 ActionRefusal::NoToken => {
781 return format!("runnerd could read no GitHub token, so it did not {asked}.");
782 }
783 ActionRefusal::Unreachable => {
784 return format!("runnerd could not reach GitHub, so it did not {asked}.");
785 }
786 ActionRefusal::RateLimited => {
787 let wait = until.map_or_else(String::new, |until| {
788 format!(
789 "; try again in {}",
790 duration(until.saturating_sub(now).max(1))
791 )
792 });
793 return match status {
794 Some(status) => format!(
795 "GitHub refused to {asked} ({status}): its rate limit is used up{wait}. Nothing was done."
796 ),
797 None => {
798 format!("GitHub's rate limit is used up, so runnerd did not {asked}{wait}.")
799 }
800 };
801 }
802 ActionRefusal::Withdrawn => {
803 return format!(
804 "runnerd did not {asked}: its config changed before the request went out (job actions turned off, \
805 or the repositories changed). Nothing was sent."
806 );
807 }
808 ActionRefusal::Unauthorized => "it refused the token".to_owned(),
809 ActionRefusal::Forbidden if rerun => format!(
810 "the token may lack Actions: write (or the repo scope) on {repository}, or the run has not finished"
811 ),
812 ActionRefusal::Forbidden => {
813 format!("the token may lack Actions: write (or the repo scope) on {repository}")
814 }
815 ActionRefusal::NotFound => {
816 "it does not show the run to this token, or the run is gone".to_owned()
817 }
818 ActionRefusal::Conflict => "the run's state does not allow it now".to_owned(),
819 ActionRefusal::Unprocessable => "it cannot do that for this run".to_owned(),
820 ActionRefusal::Failed | ActionRefusal::Other => "it failed".to_owned(),
821 };
822 let status = status.map_or_else(String::new, |status| format!(" ({status})"));
823 format!("GitHub refused to {asked}{status}: {why}. Nothing was done.")
824}
825
826fn unknown(target: &ActionTarget, cause: UnknownCause, status: Option<u16>) -> String {
827 let why = match cause {
828 UnknownCause::TimedOut => "GitHub did not answer in time".to_owned(),
829 UnknownCause::Broken => "the connection broke after the request went out".to_owned(),
830 UnknownCause::ServerError => match status {
831 Some(status) => format!(
832 "GitHub answered {status}, a server error, which does not say whether it acted"
833 ),
834 None => "GitHub answered with a server error, which does not say whether it acted"
835 .to_owned(),
836 },
837 UnknownCause::Stopping => "runnerd began to stop while GitHub was asked".to_owned(),
838 };
839 let asked = asked(target);
840 format!(
841 "runnerd cannot tell whether GitHub did {asked}: {why}. Check the run on GitHub before asking again."
842 )
843}
844
845#[cfg(all(test, any(feature = "host", feature = "client")))]
846mod tests;