1use std::collections::BTreeMap;
41use std::future::Future;
42use std::path::{Path, PathBuf};
43use std::pin::Pin;
44use std::time::Duration;
45
46use anyhow::{Result, bail};
47use serde::{Deserialize, Serialize};
48
49use crate::ask::{Answer, Question, Questions};
50use crate::land::{self, PrLifecycle, RollupView, Verdict};
51use crate::notices::{self, Link, Notice, Notices};
52use crate::release_local::{self, Job};
53use crate::run::RunState;
54
55const LAP: Duration = Duration::from_secs(300);
57
58pub(crate) const RERUN_GRACE: i64 = 180;
62
63pub const RERUN_AGAIN: &str = "rerun again";
66pub const HOLD: &str = "hold";
68pub const LEAVE_IT: &str = "leave it";
70pub const RETRY: &str = "retry";
72
73#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) enum Step {
76 Done,
78 Wait,
80 Unknown,
82 Rerun(Vec<String>),
84 Escalate(Why),
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub(crate) enum Why {
90 StillRed,
92 Stalled,
94}
95
96#[derive(Debug, Clone, Default, Serialize, Deserialize)]
98#[serde(default)]
99pub(crate) struct WatchState {
100 pub repo: String,
102 pub url: String,
103 pub head: String,
105 pub reruns: BTreeMap<String, i64>,
107 pub fingerprint: String,
109 pub progress_at: i64,
110 pub question: Option<String>,
112 pub held: Option<String>,
114 pub ignored: bool,
116 pub applied: Vec<String>,
118 pub asked_head: Option<String>,
120 pub held_head: Option<String>,
123 pub run: Option<String>,
126 pub held_task: Option<String>,
129 pub job: Option<Job>,
131 pub local: bool,
134}
135
136impl WatchState {
137 fn is_local(&self) -> bool {
141 self.local
142 || self.run.is_some()
143 || self.asked_head.is_some()
144 || self.held_head.is_some()
145 || self.job.is_some()
146 }
147}
148
149pub(crate) fn is_failed(v: Verdict) -> bool {
150 v == Verdict::Fail
151}
152
153pub(crate) fn fingerprint(snap: &RollupView) -> String {
155 let mut parts: Vec<String> = snap
156 .checks
157 .iter()
158 .map(|c| format!("{}={:?}", c.name, c.verdict))
159 .collect();
160 parts.sort();
161 format!("{}|{}", snap.head, parts.join(","))
162}
163
164pub(crate) fn observe(st: &mut WatchState, snap: &RollupView, now: i64) {
167 if st.head != snap.head {
168 st.reruns.clear();
169 st.head = snap.head.clone();
170 }
171 let fp = fingerprint(snap);
172 if st.fingerprint != fp {
173 st.fingerprint = fp;
174 st.progress_at = now;
175 }
176}
177
178pub(crate) fn decide(
181 snap: Option<&RollupView>,
182 st: &WatchState,
183 now: i64,
184 stall_secs: i64,
185) -> Step {
186 let Some(snap) = snap else {
187 return Step::Unknown;
188 };
189 if snap.state != PrLifecycle::Open {
190 return Step::Done;
191 }
192 if st.ignored || st.held.as_deref() == Some(fingerprint(snap).as_str()) {
193 return Step::Wait;
194 }
195
196 let any_pending = snap.checks.iter().any(|c| c.verdict == Verdict::Pending);
197 let complete = |run: &str| {
200 !snap
201 .checks
202 .iter()
203 .any(|c| c.verdict == Verdict::Pending && c.run.as_deref() == Some(run))
204 };
205 let mut fresh = Vec::new();
206 let mut spent_recently = false;
207 let mut spent = false;
208 let mut external = false;
209 for c in snap.checks.iter().filter(|c| is_failed(c.verdict)) {
210 match c.run.as_deref() {
211 None => external = true,
212 Some(run) if !complete(run) => {}
213 Some(run) => match st.reruns.get(run) {
214 None => {
215 if !fresh.iter().any(|r: &String| r == run) {
216 fresh.push(run.to_owned());
217 }
218 }
219 Some(&at) if now - at < RERUN_GRACE => spent_recently = true,
220 Some(_) => spent = true,
221 },
222 }
223 }
224 if !fresh.is_empty() {
225 return Step::Rerun(fresh);
226 }
227 if spent_recently {
228 return Step::Wait;
229 }
230 if spent || (external && !any_pending) {
231 return Step::Escalate(Why::StillRed);
232 }
233 if stall_secs > 0 && now - st.progress_at >= stall_secs {
234 return Step::Escalate(Why::Stalled);
235 }
236 Step::Wait
237}
238
239pub(crate) fn pr_key(url: &str) -> Option<String> {
241 let rest = url.split("://").nth(1)?;
242 let mut it = rest.split('/');
243 let _host = it.next()?;
244 let owner = it.next()?;
245 let repo = it.next()?;
246 if it.next()? != "pull" {
247 return None;
248 }
249 let n: String = it
250 .next()?
251 .chars()
252 .take_while(char::is_ascii_digit)
253 .collect();
254 (!n.is_empty()).then(|| format!("{owner}/{repo}#{n}"))
255}
256
257fn notice_key(pr: &str) -> String {
258 format!("release-pr:{pr}")
259}
260
261fn rerun_message(pr: &str) -> String {
263 format!("Release PR {pr}: failed checks were rerun once")
264}
265
266fn human_message(pr: &str) -> String {
267 format!("Release PR {pr} is stuck and needs a human")
268}
269
270fn failed_workflows(snap: &RollupView) -> Vec<String> {
271 snap.checks
272 .iter()
273 .filter(|c| is_failed(c.verdict))
274 .filter_map(|c| c.run.clone())
275 .collect::<std::collections::BTreeSet<_>>()
276 .into_iter()
277 .collect()
278}
279
280fn maintenance_choices(snap: &RollupView) -> Vec<String> {
281 let mut choices = vec![HOLD.to_owned(), LEAVE_IT.to_owned()];
282 if !failed_workflows(snap).is_empty() {
283 choices.insert(0, RERUN_AGAIN.to_owned());
284 }
285 choices
286}
287
288fn question_detail(snap: &RollupView, why: Why, st: &WatchState) -> String {
289 let mut s = String::new();
290 s.push_str(&format!("Pull request: {}\n\n", snap.url));
291 s.push_str(match why {
292 Why::StillRed => "Checks are still red after the failed jobs were rerun once.\n\n",
293 Why::Stalled => "The pull request has made no progress for too long.\n\n",
294 });
295 let failed: Vec<_> = snap
296 .checks
297 .iter()
298 .filter(|c| is_failed(c.verdict))
299 .collect();
300 if failed.is_empty() {
301 s.push_str("No check is failing.\n");
302 } else {
303 s.push_str("Failed jobs:\n");
304 for c in failed {
305 match &c.url {
306 Some(u) => s.push_str(&format!("- {} ({u})\n", c.name)),
307 None => s.push_str(&format!("- {}\n", c.name)),
308 }
309 }
310 }
311 s.push_str(&format!(
312 "\nWorkflow runs rerun so far: {}.\n\n\
313 - `{RERUN_AGAIN}`: rerun the failed jobs once more.\n\
314 - `{HOLD}`: stay quiet until a check or the head changes.\n\
315 - `{LEAVE_IT}`: stop watching this pull request.\n\n\
316 Nothing is merged or pushed by magi; silence is a hold.\n",
317 st.reruns.len()
318 ));
319 if failed_workflows(snap).is_empty() {
320 s = s.replace(
321 &format!("- `{RERUN_AGAIN}`: rerun the failed jobs once more.\n"),
322 "",
323 );
324 }
325 s
326}
327
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub(crate) enum Approved {
331 NoQuestion,
333 Open,
335 Merge,
337 Hold,
339}
340
341#[derive(Debug, Clone, PartialEq, Eq)]
343pub(crate) enum LocalStep {
344 Wait,
346 Ask,
348 Merge(String),
350 Hold(String),
352}
353
354pub(crate) fn decide_local(
362 head: &str,
363 st: &WatchState,
364 approved: Approved,
365 ask_first: bool,
366) -> LocalStep {
367 if st.ignored || st.held_head.as_deref() == Some(head) {
368 return LocalStep::Wait;
369 }
370 let about_this_head = st.asked_head.as_deref() == Some(head);
371 match approved {
372 Approved::Open => LocalStep::Wait,
373 Approved::NoQuestion if !ask_first => LocalStep::Merge(head.to_owned()),
374 Approved::NoQuestion => LocalStep::Ask,
375 Approved::Merge if about_this_head => LocalStep::Merge(head.to_owned()),
376 Approved::Hold if about_this_head => LocalStep::Hold(head.to_owned()),
377 Approved::Merge | Approved::Hold if !ask_first => LocalStep::Merge(head.to_owned()),
379 Approved::Merge | Approved::Hold => LocalStep::Ask,
380 }
381}
382
383pub(crate) fn register(home: &Path, repo: &Path, url: &str, run: &str) {
386 let Some(pr) = pr_key(url) else {
387 return;
388 };
389 let w = Watcher::new(Box::new(GhForge), home.to_path_buf());
390 if w.state_path(&pr).exists() {
391 return;
392 }
393 let st = WatchState {
394 repo: repo.to_string_lossy().into_owned(),
395 url: url.to_owned(),
396 run: Some(run.to_owned()),
397 local: true,
398 ..WatchState::default()
399 };
400 w.save(&pr, &st);
401}
402
403pub(crate) fn states_for_questions(home: &Path, questions: &[Question]) -> Vec<WatchState> {
405 if !questions
406 .iter()
407 .any(|q| q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")
408 {
409 return Vec::new();
410 }
411 Watcher::new(Box::new(GhForge), home.to_path_buf()).stored()
412}
413
414pub(crate) fn state_for_question(home: &Path, question_id: &str) -> Option<WatchState> {
417 Watcher::new(Box::new(GhForge), home.to_path_buf())
418 .stored()
419 .into_iter()
420 .find(|s| s.question.as_deref() == Some(question_id))
421}
422
423pub(crate) fn question_for_notice(home: &Path, key: &str) -> Option<String> {
425 let pr = key.strip_prefix("release-pr:")?;
426 let state = Watcher::new(Box::new(GhForge), home.to_path_buf()).load(pr);
427 (pr_key(&state.url).as_deref() == Some(pr))
428 .then_some(state.question)
429 .flatten()
430}
431
432pub fn task_of_question(
437 home: &Path,
438 q: &Question,
439 queue: &crate::queue::Queue,
440) -> Option<crate::queue::Task> {
441 let run = state_for_question(home, &q.id)?.run?;
442 queue.list().into_iter().find(|t| t.runs.contains(&run))
443}
444
445pub(crate) fn approval_target(home: &Path, q: &Question) -> Option<crate::merge_decision::Target> {
448 if q.node != crate::bump::NOTICE_NODE
449 || q.seat != "release-watch"
450 || !q.choices.iter().any(|c| c == land::APPROVE)
451 {
452 return None;
453 }
454 let state = state_for_question(home, &q.id)?;
455 Some(crate::merge_decision::Target {
456 pr: state.url,
457 head: state.asked_head?,
458 language: "en".into(),
459 })
460}
461
462pub(crate) fn deputy_brief(q: &Question, home: &Path) -> String {
464 let mut s = String::from(
465 "This question was filed by magi's release watcher about a release pull \
466 request. Whatever the owner picks, only the watcher acts on it, on its \
467 next lap; you apply nothing and never close, merge, rerun or push \
468 anything. Silence is a hold.",
469 );
470 match state_for_question(home, &q.id) {
471 Some(st) => {
472 s.push_str(&format!(
473 "\n\nPull request: {}\nCheckout: {}",
474 st.url, st.repo
475 ));
476 }
477 None => s.push_str(
478 "\n\nThe watcher's record for this question could not be found, so the \
479 pull request is known to you only through the question's own text. \
480 Say so to the owner rather than guessing.",
481 ),
482 }
483 if let Some(target) = &q.merge_target {
484 s.push_str(&format!("\n\nThis approval is bound to PR {} at head `{}`. A deputy merge requires the owner's whole latest message and quote to be exactly `merge {}`. A standing conversation can bind it as `{}: merge {}`. A generic batch instruction never authorizes merge.", target.pr, target.head, target.head, q.id, target.head));
485 }
486 s.push_str("\n\nWhat each option does:");
487 for c in &q.choices {
488 let what = match c.as_str() {
489 RERUN_AGAIN => {
490 "the daemon reruns the recorded failed workflows once if the PR head still matches"
491 }
492 HOLD if q.choices.iter().any(|c| c == land::APPROVE) => {
493 "leave the pull request open and unmerged; ask again only when the head moves"
494 }
495 HOLD => "stay quiet until a check or the head changes",
496 LEAVE_IT => {
497 "stop watching this pull request and dismiss its notice. It does NOT \
498 close the pull request"
499 }
500 RETRY => "run the failed release again from where it stopped",
501 land::APPROVE => {
502 "squash-merge exactly the head the question names - irreversible - \
503 then tag and release"
504 }
505 _ => "recorded as the answer",
506 };
507 s.push_str(&format!("\n- `{c}`: {what}"));
508 }
509 s.push_str(
510 "\n\nIf the owner's words ask for the pull request itself to be closed, that \
511 is something only they can do by hand; do not read it as a choice unless \
512 it plainly means stop watching.",
513 );
514 s
515}
516
517const HOLD_PREFIX: &str = "[release] ";
520
521fn approval_message(pr: &str) -> String {
522 format!("Release PR {pr} is waiting for your approval to merge")
523}
524
525fn failed_message(pr: &str) -> String {
526 format!("Release PR {pr} merged but the release is on hold")
527}
528
529fn released_key(pr: &str) -> String {
530 format!("release-done:{pr}")
531}
532
533type Fut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
534
535pub(crate) trait ReleaseForge: Send + Sync {
537 fn list<'a>(&'a self, repo: &'a Path) -> Fut<'a, Result<Vec<(String, String)>>>;
539 fn snapshot<'a>(&'a self, repo: &'a Path, url: &'a str) -> Fut<'a, Result<RollupView>>;
540 fn rerun<'a>(&'a self, repo: &'a Path, run: &'a str) -> Fut<'a, Result<()>>;
541 fn config<'a>(&'a self, _repo: &'a Path) -> Fut<'a, Result<crate::config::Config>> {
543 Box::pin(async { Ok(crate::config::Config::default()) })
544 }
545 fn land_approval<'a>(&'a self, _repo: &'a Path) -> Fut<'a, Result<bool>> {
548 Box::pin(async { Ok(true) })
549 }
550 fn info<'a>(&'a self, _repo: &'a Path, url: &'a str) -> Fut<'a, Result<PrInfo>> {
552 Box::pin(async move { bail!("no pull request info for {url}") })
553 }
554 fn merge<'a>(&'a self, _repo: &'a Path, url: &'a str, _head: &'a str) -> Fut<'a, Result<bool>> {
557 Box::pin(async move { bail!("cannot merge {url}") })
558 }
559}
560
561#[derive(Debug, Clone, Default, PartialEq, Eq)]
563pub(crate) struct PrInfo {
564 pub branch: String,
566 pub merge_commit: Option<String>,
568 pub title: String,
570}
571
572pub(crate) fn parse_info(json: &str) -> Result<PrInfo> {
574 let v: serde_json::Value = serde_json::from_str(json)?;
575 let text = |k: &str| {
576 v.get(k)
577 .and_then(|x| x.as_str())
578 .unwrap_or_default()
579 .to_owned()
580 };
581 Ok(PrInfo {
582 branch: text("headRefName"),
583 title: text("title"),
584 merge_commit: v
585 .get("mergeCommit")
586 .and_then(|m| m.get("oid"))
587 .and_then(|o| o.as_str())
588 .filter(|o| !o.is_empty())
589 .map(str::to_owned),
590 })
591}
592
593pub(crate) struct GhForge;
595
596impl ReleaseForge for GhForge {
597 fn list<'a>(&'a self, repo: &'a Path) -> Fut<'a, Result<Vec<(String, String)>>> {
598 Box::pin(crate::bump::list_open_release_prs(repo))
599 }
600
601 fn snapshot<'a>(&'a self, repo: &'a Path, url: &'a str) -> Fut<'a, Result<RollupView>> {
602 Box::pin(async move {
603 let args = [
604 "pr".to_owned(),
605 "view".to_owned(),
606 url.to_owned(),
607 "--json".to_owned(),
608 "url,number,state,headRefOid,statusCheckRollup".to_owned(),
609 ];
610 let (ok, out) = land::gh(repo, &args).await?;
611 if !ok {
612 bail!("gh pr view {url}: {out}");
613 }
614 land::parse_rollup(&out)
615 })
616 }
617
618 fn rerun<'a>(&'a self, repo: &'a Path, run: &'a str) -> Fut<'a, Result<()>> {
619 Box::pin(async move {
620 let args = [
621 "run".to_owned(),
622 "rerun".to_owned(),
623 run.to_owned(),
624 "--failed".to_owned(),
625 ];
626 let (ok, out) = land::gh(repo, &args).await?;
627 if !ok {
628 bail!("gh run rerun {run}: {out}");
629 }
630 Ok(())
631 })
632 }
633
634 fn config<'a>(&'a self, repo: &'a Path) -> Fut<'a, Result<crate::config::Config>> {
635 Box::pin(async move { Ok(crate::config::Config::discover(repo, None)?.0) })
636 }
637
638 fn land_approval<'a>(&'a self, repo: &'a Path) -> Fut<'a, Result<bool>> {
639 Box::pin(async move {
643 Ok(crate::config::Config::discover(repo, None)?
644 .0
645 .graph
646 .land_approval)
647 })
648 }
649
650 fn info<'a>(&'a self, repo: &'a Path, url: &'a str) -> Fut<'a, Result<PrInfo>> {
651 Box::pin(async move {
652 let args = [
653 "pr".to_owned(),
654 "view".to_owned(),
655 url.to_owned(),
656 "--json".to_owned(),
657 "headRefName,mergeCommit,title".to_owned(),
658 ];
659 let (ok, out) = land::gh(repo, &args).await?;
660 if !ok {
661 bail!("gh pr view {url}: {out}");
662 }
663 parse_info(&out)
664 })
665 }
666
667 fn merge<'a>(&'a self, repo: &'a Path, url: &'a str, head: &'a str) -> Fut<'a, Result<bool>> {
668 Box::pin(async move {
669 let title = self
670 .info(repo, url)
671 .await
672 .map(|i| i.title)
673 .unwrap_or_default();
674 let title = if title.trim().is_empty() {
675 "chore: release".to_owned()
676 } else {
677 title
678 };
679 let mut argv = crate::bump::bump_merge_argv(url, &title);
682 argv.push("--match-head-commit".to_owned());
683 argv.push(head.to_owned());
684 let (ok, out) = land::gh(repo, &argv).await?;
685 if ok {
686 return Ok(true);
687 }
688 let after = land::lifecycle(repo, url).await.ok();
691 if land::merged_after_all(&argv, &out, after).is_some() {
692 return Ok(true);
693 }
694 bail!("gh pr merge {url}: {out}")
695 })
696 }
697}
698
699pub(crate) struct Watcher {
701 forge: Box<dyn ReleaseForge>,
702 home: PathBuf,
703}
704
705impl Watcher {
706 pub(crate) fn new(forge: Box<dyn ReleaseForge>, home: PathBuf) -> Self {
707 Self { forge, home }
708 }
709
710 fn dir(&self) -> PathBuf {
711 self.home.join("release-watch")
712 }
713
714 fn state_path(&self, pr: &str) -> PathBuf {
715 self.dir().join(format!("{}.json", notices::id_of(pr)))
716 }
717
718 fn load(&self, pr: &str) -> WatchState {
719 std::fs::read_to_string(self.state_path(pr))
720 .ok()
721 .and_then(|s| serde_json::from_str(&s).ok())
722 .unwrap_or_default()
723 }
724
725 fn save(&self, pr: &str, st: &WatchState) -> bool {
726 let write = || -> Result<()> {
727 std::fs::create_dir_all(self.dir())?;
728 let path = self.state_path(pr);
729 let tmp = path.with_extension("json.tmp");
730 std::fs::write(&tmp, serde_json::to_string_pretty(st)?)?;
731 std::fs::rename(&tmp, &path)?;
732 Ok(())
733 };
734 match write() {
735 Ok(()) => true,
736 Err(e) => {
737 tracing::warn!("could not save the release watch for {pr}: {e:#}");
738 false
739 }
740 }
741 }
742
743 fn stored(&self) -> Vec<WatchState> {
745 let Ok(rd) = std::fs::read_dir(self.dir()) else {
746 return Vec::new();
747 };
748 rd.flatten()
749 .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
750 .filter_map(|e| std::fs::read_to_string(e.path()).ok())
751 .filter_map(|s| serde_json::from_str(&s).ok())
752 .collect()
753 }
754
755 fn questions(&self) -> Questions {
756 Questions::at(self.home.join("questions"))
757 }
758
759 fn raise(&self, pr: &str, url: &str, message: String) {
760 notices::raise_in(
761 &self.home,
762 Notice::warn(¬ice_key(pr), message).link(Link::Url {
763 url: url.to_owned(),
764 }),
765 );
766 }
767
768 pub(crate) async fn lap(
771 &self,
772 repos: &[PathBuf],
773 stall_secs: i64,
774 now: i64,
775 halt: &(dyn Fn() -> bool + Sync),
776 ) {
777 let stored = self.stored();
778 let mut repos = repos.to_vec();
780 for s in &stored {
781 let p = PathBuf::from(&s.repo);
782 if !s.repo.is_empty() && !repos.contains(&p) {
783 repos.push(p);
784 }
785 }
786 for repo in &repos {
787 if halt() {
788 return;
789 }
790 let mut urls: Vec<String> = match self.forge.list(repo).await {
791 Ok(v) => v.into_iter().map(|(_, u)| u).collect(),
792 Err(e) => {
793 tracing::warn!(
794 "could not list release pull requests in {}: {e:#}",
795 repo.display()
796 );
797 Vec::new()
798 }
799 };
800 let here = repo.to_string_lossy();
803 for s in stored.iter().filter(|s| s.repo == here.as_ref()) {
804 if !urls.contains(&s.url) {
805 urls.push(s.url.clone());
806 }
807 }
808 for url in urls {
809 if halt() {
810 return;
811 }
812 self.watch(repo, &url, stall_secs, now, halt).await;
813 }
814 }
815 }
816
817 pub(crate) async fn watch(
819 &self,
820 repo: &Path,
821 url: &str,
822 stall_secs: i64,
823 now: i64,
824 halt: &(dyn Fn() -> bool + Sync),
825 ) {
826 let Some(pr) = pr_key(url) else {
827 tracing::warn!("not a pull request url: {url}");
828 return;
829 };
830 let mut st = self.load(&pr);
831 st.repo = repo.to_string_lossy().into_owned();
832 st.url = url.to_owned();
833
834 let snap = match self.forge.snapshot(repo, url).await {
835 Ok(s) => Some(s),
836 Err(e) => {
837 tracing::warn!("could not read {url}: {e:#}");
838 None
839 }
840 };
841 match self.forge.config(repo).await {
842 Ok(cfg) if cfg.release.is_local() => {
843 st.local = true;
844 self.watch_local(repo, &pr, st, snap, Some(&cfg)).await;
845 return;
846 }
847 Ok(_) => st.local = false,
848 Err(e) if st.is_local() => {
849 tracing::warn!(
850 "could not read the config of {}: {e:#}; watching {url} as a local release without it",
851 repo.display()
852 );
853 self.watch_local(repo, &pr, st, snap, None).await;
854 return;
855 }
856 Err(e) => tracing::warn!(
857 "could not read the config of {}: {e:#}; watching {url} as an Actions release",
858 repo.display()
859 ),
860 }
861 if decide(snap.as_ref(), &st, now, stall_secs) == Step::Done {
862 self.finish(&pr, &st);
863 return;
864 }
865 let Some(snap) = snap else {
866 return;
867 };
868
869 if let Some(id) = st.question.clone() {
871 match self.questions().get(&id) {
872 Ok(q) if q.status.open() => return,
873 Ok(q) => self.apply_answer(&pr, &mut st, &snap, &q, now),
874 Err(_) => st.question = None,
875 }
876 observe(&mut st, &snap, now);
878 self.save(&pr, &st);
879 } else {
880 observe(&mut st, &snap, now);
881 }
882
883 match decide(Some(&snap), &st, now, stall_secs) {
884 Step::Done | Step::Unknown | Step::Wait => {}
885 Step::Rerun(runs) => {
886 for r in &runs {
888 st.reruns.insert(r.clone(), now);
889 }
890 if !self.save(&pr, &st) || halt() {
893 return;
894 }
895 let mut ok = false;
896 for r in &runs {
897 match self.forge.rerun(repo, r).await {
898 Ok(()) => ok = true,
899 Err(e) => tracing::warn!("could not rerun run {r} of {url}: {e:#}"),
900 }
901 }
902 if ok {
903 self.raise(&pr, url, rerun_message(&pr));
904 }
905 }
906 Step::Escalate(why) => {
907 self.raise(&pr, url, human_message(&pr));
908 let mut q = Question::new(
909 String::new(),
910 crate::bump::NOTICE_NODE.to_owned(),
911 "release-watch".to_owned(),
912 format!("Release PR {pr} is stuck: what now?"),
913 question_detail(&snap, why, &st),
914 maintenance_choices(&snap),
915 );
916 if q.choices.iter().any(|c| c == RERUN_AGAIN) {
917 q.actions.insert(
918 RERUN_AGAIN.into(),
919 crate::ask::ChoiceAction::RerunChecks {
920 repo: repo.to_path_buf(),
921 pr: snap.url.clone(),
922 head: snap.head.clone(),
923 runs: failed_workflows(&snap).into_iter().take(20).collect(),
924 },
925 );
926 }
927 match self.questions().put_executable(&mut q) {
928 Ok(()) => st.question = Some(q.id.clone()),
929 Err(e) => tracing::warn!("could not file the question for {pr}: {e:#}"),
930 }
931 }
932 }
933 self.save(&pr, &st);
934 }
935
936 async fn watch_local(
938 &self,
939 repo: &Path,
940 pr: &str,
941 mut st: WatchState,
942 snap: Option<RollupView>,
943 cfg: Option<&crate::config::Config>,
944 ) {
945 let Some(snap) = snap else {
946 return;
947 };
948 match snap.state {
949 PrLifecycle::Closed => self.finish(pr, &st),
950 PrLifecycle::Merged => match cfg {
951 Some(cfg) => self.release_merged(repo, pr, st, cfg).await,
952 None => {
954 tracing::warn!("{pr} is merged but its config is unreadable; not released yet")
955 }
956 },
957 PrLifecycle::Open => {
958 let approved = match st.question.clone() {
959 None => Approved::NoQuestion,
960 Some(id) => match self.questions().get(&id) {
961 Ok(q) if q.status.open() => Approved::Open,
962 Ok(q) => match &q.answer {
963 Some(Answer::Choice(c))
964 if land::approval(Some(c)) == land::Approval::Merge =>
965 {
966 Approved::Merge
967 }
968 _ => Approved::Hold,
969 },
970 Err(_) => Approved::NoQuestion,
971 },
972 };
973 let ask_first = if cfg.is_none() {
974 true
975 } else {
976 match self.forge.land_approval(repo).await {
977 Ok(v) => v,
978 Err(e) => {
979 tracing::warn!("could not read graph.land_approval for {pr}: {e:#}");
980 true
981 }
982 }
983 };
984 let step = decide_local(&snap.head, &st, approved, ask_first);
985 if cfg.is_none() && matches!(step, LocalStep::Merge(_)) {
986 tracing::warn!("not merging {pr} while its config is unreadable");
988 return;
989 }
990 if matches!(
991 step,
992 LocalStep::Merge(_) | LocalStep::Hold(_) | LocalStep::Ask
993 ) {
994 st.question = None;
996 }
997 match step {
998 LocalStep::Wait => {}
999 LocalStep::Hold(head) => st.held_head = Some(head),
1000 LocalStep::Ask => {
1001 st.held_head = None;
1002 st.asked_head = Some(snap.head.clone());
1003 self.raise(pr, &snap.url, approval_message(pr));
1004 let mut q = Question::new(
1005 String::new(),
1006 crate::bump::NOTICE_NODE.to_owned(),
1007 "release-watch".to_owned(),
1008 format!("Release PR {pr}: merge it and release?"),
1009 format!(
1010 "Pull request: {}\nHead: {}\n\n\
1011 `[release] mode = \"local\"`: no CI is awaited. `{}` merges \
1012 exactly this head, then magi tags the merge commit and runs the \
1013 configured release commands. `{}` leaves the pull request \
1014 open. Silence is a hold.\n",
1015 snap.url,
1016 snap.head,
1017 land::APPROVE,
1018 land::HOLD
1019 ),
1020 vec![land::APPROVE.to_owned(), land::HOLD.to_owned()],
1021 );
1022 q.merge_target = Some(crate::merge_decision::Target {
1023 pr: snap.url.clone(),
1024 head: snap.head.clone(),
1025 language: "en".into(),
1026 });
1027 match self.questions().put_executable(&mut q) {
1028 Ok(()) => st.question = Some(q.id.clone()),
1029 Err(e) => tracing::warn!("could not file the question for {pr}: {e:#}"),
1030 }
1031 }
1032 LocalStep::Merge(head) => {
1033 match self.forge.merge(repo, &snap.url, &head).await {
1034 Ok(true) => {
1035 self.save(pr, &st);
1037 if let Some(cfg) = cfg {
1038 self.release_merged(repo, pr, st, cfg).await;
1039 }
1040 return;
1041 }
1042 res => {
1043 match res {
1044 Err(e) => {
1045 tracing::warn!("could not merge {}: {e:#}", snap.url)
1046 }
1047 _ => tracing::warn!("{} did not merge", snap.url),
1048 }
1049 st.held_head = Some(head);
1050 self.raise(
1051 pr,
1052 &snap.url,
1053 format!(
1054 "Release PR {pr} could not be merged; merge it by hand"
1055 ),
1056 );
1057 }
1058 }
1059 }
1060 }
1061 self.save(pr, &st);
1062 }
1063 }
1064 }
1065
1066 async fn release_merged(
1068 &self,
1069 repo: &Path,
1070 pr: &str,
1071 mut st: WatchState,
1072 cfg: &crate::config::Config,
1073 ) {
1074 if st.ignored {
1075 return self.finish(pr, &st);
1076 }
1077 if st.job.is_none() {
1078 let info = match self.forge.info(repo, &st.url).await {
1079 Ok(i) => i,
1080 Err(e) => {
1081 tracing::warn!("could not read the merged {}: {e:#}", st.url);
1082 return;
1083 }
1084 };
1085 let (Some(version), Some(commit)) = (
1086 release_local::version_from_branch(&info.branch),
1087 info.merge_commit,
1088 ) else {
1089 if release_local::version_from_branch(&info.branch).is_none() {
1092 self.finish(pr, &st);
1093 }
1094 return;
1095 };
1096 let mut job = Job::new(&version, &st.url, &commit);
1097 job.accepted = release_local::version_from_title(&info.title)
1100 .into_iter()
1101 .filter(|t| *t != version)
1102 .collect();
1103 st.job = Some(job);
1104 if !self.save(pr, &st) {
1105 return;
1106 }
1107 }
1108 let Some(mut job) = st.job.take() else {
1109 return;
1110 };
1111 if job.finished {
1112 st.job = Some(job);
1115 if !self.record_on_run(&st) {
1116 self.save(pr, &st);
1117 return;
1118 }
1119 return self.complete(pr, &mut st);
1120 }
1121 if job.interrupted() {
1122 job.failed = Some(format!(
1123 "magi stopped while `{}` was running; it may have partly run, so it is not repeated on its own",
1124 job.running.clone().unwrap_or_default()
1125 ));
1126 }
1127 if let Some(why) = job.failed.clone() {
1128 self.hold_task(&mut st, &format!("release {} is on hold: {why}", job.tag()));
1131 let retry = self.settle_job_question(pr, &mut st, &mut job);
1133 if !retry {
1134 st.job = Some(job);
1135 self.save(pr, &st);
1136 return;
1137 }
1138 }
1139 let shell = cfg.shell();
1140 let env = release_local::Env {
1141 repo,
1142 home: &self.home,
1143 key: pr,
1144 remote: &cfg.merge.remote,
1145 shell: &shell,
1146 release: &cfg.release,
1147 };
1148 let result = {
1149 let mut save = |j: &Job| {
1150 let mut copy = st.clone();
1151 copy.job = Some(j.clone());
1152 self.save(pr, ©)
1153 };
1154 release_local::run_job(&env, &mut job, &mut save).await
1155 };
1156 match result {
1157 Ok(()) => {
1158 self.raise_released(pr, &st.url, &job);
1159 st.job = Some(job);
1160 if self.record_on_run(&st) {
1161 self.complete(pr, &mut st);
1162 } else {
1163 self.save(pr, &st);
1166 }
1167 }
1168 Err(e) => {
1169 job.failed = Some(format!("{e:#}"));
1170 self.hold_task(&mut st, &format!("release {} failed: {e:#}", job.tag()));
1171 self.raise(pr, &st.url, failed_message(pr));
1172 self.file_job_question(pr, &mut st, &job);
1173 st.job = Some(job);
1174 self.save(pr, &st);
1175 self.record_on_run(&st);
1176 }
1177 }
1178 }
1179
1180 fn record_on_run(&self, st: &WatchState) -> bool {
1185 let (Some(run), Some(job)) = (st.run.as_deref(), st.job.as_ref()) else {
1186 return true;
1187 };
1188 let mut state = match RunState::load_under(run, &self.home) {
1189 Ok(s) => s,
1190 Err(e) => {
1191 tracing::warn!("could not record the release on run {run}: {e:#}");
1192 return true;
1193 }
1194 };
1195 let bump = state.release_bump.get_or_insert_with(Default::default);
1196 if bump.release.as_ref() == Some(job) {
1197 return true;
1198 }
1199 bump.release = Some(job.clone());
1200 state.event(
1201 "release",
1202 format!(
1203 "release {} {}",
1204 job.tag(),
1205 if job.finished {
1206 "finished"
1207 } else if let Some(why) = &job.failed {
1208 why
1209 } else {
1210 "stopped"
1211 }
1212 ),
1213 );
1214 match state.save_under(&self.home) {
1215 Ok(()) => true,
1216 Err(e) => {
1217 tracing::warn!("could not save the release on run {run}: {e:#}");
1218 false
1219 }
1220 }
1221 }
1222
1223 fn hold_task(&self, st: &mut WatchState, reason: &str) {
1227 if st.held_task.is_some() {
1228 return;
1229 }
1230 let Some(run) = st.run.clone() else {
1231 return;
1232 };
1233 let q = crate::queue::Queue::at(self.home.join("queue"));
1234 for mut t in q.list() {
1235 if t.runs.contains(&run) {
1236 if t.status != crate::queue::TaskStatus::Held {
1237 t.notice_cause("release-failed", Some(&run), None);
1238 t.hold_machine(Some(format!("{HOLD_PREFIX}{reason}")));
1239 match q.put(&mut t) {
1240 Ok(()) => st.held_task = Some(t.id.clone()),
1241 Err(e) => tracing::warn!("could not hold task {} for {run}: {e:#}", t.id),
1242 }
1243 }
1244 return;
1245 }
1246 }
1247 }
1248
1249 #[must_use]
1256 fn unhold_task(&self, st: &mut WatchState) -> bool {
1257 let Some(id) = st.held_task.take() else {
1258 return true;
1259 };
1260 let q = crate::queue::Queue::at(self.home.join("queue"));
1261 let mut t = match q.get(&id) {
1262 Ok(t) => t,
1263 Err(_) if matches!(q.path_of(&id).try_exists(), Ok(false)) => return true,
1266 Err(e) => {
1267 tracing::warn!("could not read task {id} to restore it after the release: {e:#}");
1268 st.held_task = Some(id);
1269 return false;
1270 }
1271 };
1272 let ours = t.status == crate::queue::TaskStatus::Held
1273 && t.hold_source == Some(crate::queue::HoldSource::Machine)
1274 && t.hold_reason
1275 .as_deref()
1276 .is_some_and(|r| r.starts_with(HOLD_PREFIX));
1277 if ours {
1278 t.succeed();
1279 if let Err(e) = q.put(&mut t) {
1280 tracing::warn!("could not restore task {id} after the release: {e:#}");
1281 st.held_task = Some(id);
1282 return false;
1283 }
1284 }
1285 true
1286 }
1287
1288 fn complete(&self, pr: &str, st: &mut WatchState) {
1292 if self.unhold_task(st) {
1293 self.finish(pr, st);
1294 } else {
1295 self.save(pr, st);
1296 }
1297 }
1298
1299 fn raise_released(&self, pr: &str, url: &str, job: &Job) {
1300 notices::raise_in(
1301 &self.home,
1302 Notice::info(&released_key(pr), format!("Released {} ({pr})", job.tag())).link(
1303 Link::Url {
1304 url: url.to_owned(),
1305 },
1306 ),
1307 );
1308 }
1309
1310 fn file_job_question(&self, pr: &str, st: &mut WatchState, job: &Job) {
1312 let last = job
1313 .log
1314 .last()
1315 .map(|l| format!("\nLast step: {}\n\n{}\n", l.name, l.tail))
1316 .unwrap_or_default();
1317 let mut q = Question::new(
1318 String::new(),
1319 crate::bump::NOTICE_NODE.to_owned(),
1320 "release-watch".to_owned(),
1321 format!("Release {} of {pr} is on hold: retry?", job.tag()),
1322 format!(
1323 "Pull request: {}\nWhy it stopped: {}\n{last}\n\
1324 Full output is under the magi home's release-local directory.\n\n\
1325 - `{RETRY}`: run it again from where it stopped (the tag is not \
1326 recreated and finished commands are skipped).\n\
1327 - `{LEAVE_IT}`: stop watching; release by hand.\n\n\
1328 Nothing is retried on its own; silence is a hold.\n",
1329 job.pr_url,
1330 job.failed.clone().unwrap_or_default()
1331 ),
1332 vec![RETRY.to_owned(), LEAVE_IT.to_owned()],
1333 );
1334 match self.questions().put_executable(&mut q) {
1335 Ok(()) => st.question = Some(q.id.clone()),
1336 Err(e) => tracing::warn!("could not file the question for {pr}: {e:#}"),
1337 }
1338 }
1339
1340 fn settle_job_question(&self, pr: &str, st: &mut WatchState, job: &mut Job) -> bool {
1344 let why = job.failed.clone().unwrap_or_default();
1345 if let Some(id) = st.question.clone() {
1346 match self.questions().get(&id) {
1347 Ok(q) if q.status.open() => return false,
1348 Ok(q) => {
1349 st.question = None;
1350 match &q.answer {
1351 Some(Answer::Choice(c)) if c == RETRY => {
1352 job.resume();
1353 st.held = None;
1354 return true;
1355 }
1356 Some(Answer::Choice(c)) if c == LEAVE_IT => {
1357 st.ignored = true;
1358 let _ = Notices::at(self.home.join("notifications"))
1359 .dismiss(¬ices::id_of(¬ice_key(pr)));
1360 }
1361 _ => st.held = Some(why),
1363 }
1364 return false;
1365 }
1366 Err(_) => st.question = None,
1367 }
1368 }
1369 if !st.ignored && st.held.as_deref() != Some(why.as_str()) {
1370 self.raise(pr, &st.url, failed_message(pr));
1371 self.file_job_question(pr, st, job);
1372 }
1373 false
1374 }
1375
1376 fn apply_answer(
1378 &self,
1379 pr: &str,
1380 st: &mut WatchState,
1381 snap: &RollupView,
1382 q: &Question,
1383 now: i64,
1384 ) {
1385 st.question = None;
1386 if st.applied.contains(&q.id) {
1387 return;
1388 }
1389 st.applied.push(q.id.clone());
1390 if st.applied.len() > 20 {
1391 st.applied.remove(0);
1392 }
1393 match &q.answer {
1394 Some(Answer::Choice(c)) if c == RERUN_AGAIN => {
1395 st.held = None;
1396 if let Some(crate::ask::ChoiceAction::RerunChecks { runs, .. }) = q.chosen_action()
1397 {
1398 for run in runs {
1401 st.reruns.insert(run.clone(), now);
1402 }
1403 return;
1404 }
1405 for c in snap.checks.iter().filter(|c| is_failed(c.verdict)) {
1406 if let Some(r) = &c.run {
1407 st.reruns.remove(r);
1408 }
1409 }
1410 }
1411 Some(Answer::Choice(c)) if c == LEAVE_IT => {
1412 st.ignored = true;
1413 if let Err(e) = Notices::at(self.home.join("notifications"))
1414 .dismiss(¬ices::id_of(¬ice_key(pr)))
1415 {
1416 tracing::warn!("could not dismiss the notice for {pr}: {e:#}");
1417 }
1418 }
1419 _ => st.held = Some(fingerprint(snap)),
1421 }
1422 }
1423
1424 fn finish(&self, pr: &str, st: &WatchState) {
1426 let _ =
1427 Notices::at(self.home.join("notifications")).dismiss(¬ices::id_of(¬ice_key(pr)));
1428 if let Some(id) = &st.question {
1429 let _ = self.questions().update(id, |q| {
1430 q.abandon("the release pull request is no longer open");
1431 Ok(())
1432 });
1433 }
1434 let _ = std::fs::remove_file(self.state_path(pr));
1435 }
1436}
1437
1438pub(crate) async fn run(
1442 watcher: Watcher,
1443 settings: impl Fn() -> (Vec<PathBuf>, u64),
1444 stop: crate::daemon::Stop,
1445) {
1446 let halt = {
1447 let stop = stop.clone();
1448 move || stop.stopped()
1449 };
1450 while !stop.stopped() {
1451 let (repos, minutes) = settings();
1452 if minutes > 0 {
1453 let now = jiff::Timestamp::now().as_second();
1454 watcher
1455 .lap(&repos, (minutes as i64).saturating_mul(60), now, &halt)
1456 .await;
1457 }
1458 let mut slept = Duration::ZERO;
1459 while slept < LAP && !stop.stopped() {
1460 tokio::time::sleep(Duration::from_secs(1)).await;
1461 slept += Duration::from_secs(1);
1462 }
1463 }
1464}
1465
1466#[cfg(test)]
1467mod tests {
1468 use super::*;
1469 use crate::land::CheckView;
1470 use anyhow::Context;
1471 use std::sync::Mutex;
1472
1473 const URL: &str = "https://github.com/o/r/pull/7";
1474
1475 fn check(name: &str, v: Verdict, run: Option<&str>) -> CheckView {
1476 CheckView {
1477 name: name.to_owned(),
1478 verdict: v,
1479 run: run.map(str::to_owned),
1480 url: run.map(|r| format!("https://github.com/o/r/actions/runs/{r}/job/1")),
1481 }
1482 }
1483
1484 fn snap(state: PrLifecycle, head: &str, checks: Vec<CheckView>) -> RollupView {
1485 RollupView {
1486 url: URL.to_owned(),
1487 number: 7,
1488 state,
1489 head: head.to_owned(),
1490 checks,
1491 }
1492 }
1493
1494 fn open(checks: Vec<CheckView>) -> RollupView {
1495 snap(PrLifecycle::Open, "h1", checks)
1496 }
1497
1498 fn st_at(progress: i64) -> WatchState {
1499 WatchState {
1500 progress_at: progress,
1501 ..WatchState::default()
1502 }
1503 }
1504
1505 #[test]
1506 fn release_notice_uses_saved_question_and_checks_its_current_status() {
1507 let dir = tempfile::tempdir().unwrap();
1508 let watcher = Watcher::new(Box::new(GhForge), dir.path().to_path_buf());
1509 let questions = Questions::at(dir.path().join("questions"));
1510 let mut q = Question::new(
1511 String::new(),
1512 crate::bump::NOTICE_NODE.into(),
1513 "release-watch".into(),
1514 "Release?".into(),
1515 String::new(),
1516 Vec::new(),
1517 );
1518 questions.put(&mut q).unwrap();
1519 let st = WatchState {
1520 url: "https://example.invalid/o/r/pull/7".into(),
1521 question: Some(q.id.clone()),
1522 ..WatchState::default()
1523 };
1524 assert!(watcher.save("o/r#7", &st));
1525 let n = Notice::warn("release-pr:o/r#7", "Release PR is waiting for approval.");
1526 assert_eq!(
1527 notices::answerable_question(&n, &questions),
1528 Some(q.id.clone())
1529 );
1530 questions
1531 .update(&q.id, |q| {
1532 q.abandon("obsolete approval");
1533 Ok(())
1534 })
1535 .unwrap();
1536 assert_eq!(notices::answerable_question(&n, &questions), None);
1537 assert_eq!(question_for_notice(dir.path(), "release-pr:o/r#8"), None);
1538 }
1539
1540 #[test]
1541 fn unreadable_is_unknown_and_merged_or_closed_is_done() {
1542 assert_eq!(decide(None, &st_at(0), 10, 60), Step::Unknown);
1543 for s in [PrLifecycle::Merged, PrLifecycle::Closed] {
1544 assert_eq!(
1545 decide(Some(&snap(s, "h", vec![])), &st_at(0), 10, 60),
1546 Step::Done
1547 );
1548 }
1549 }
1550
1551 #[test]
1552 fn a_failed_run_is_rerun_even_while_another_run_is_pending() {
1553 let s = open(vec![
1554 check("win", Verdict::Fail, Some("11")),
1555 check("lint", Verdict::Pending, Some("12")),
1556 ]);
1557 assert_eq!(
1558 decide(Some(&s), &st_at(0), 1, 3600),
1559 Step::Rerun(vec!["11".into()])
1560 );
1561 }
1562
1563 #[test]
1564 fn a_run_with_a_job_still_pending_is_not_complete() {
1565 let s = open(vec![
1566 check("win", Verdict::Fail, Some("11")),
1567 check("mac", Verdict::Pending, Some("11")),
1568 ]);
1569 assert_eq!(decide(Some(&s), &st_at(0), 1, 3600), Step::Wait);
1570 }
1571
1572 #[test]
1573 fn one_rerun_per_run_then_grace_then_escalation() {
1574 let s = open(vec![check("win", Verdict::Fail, Some("11"))]);
1575 let mut st = st_at(0);
1576 st.reruns.insert("11".into(), 100);
1577 assert_eq!(decide(Some(&s), &st, 100 + RERUN_GRACE - 1, 0), Step::Wait);
1578 assert_eq!(
1579 decide(Some(&s), &st, 100 + RERUN_GRACE, 0),
1580 Step::Escalate(Why::StillRed)
1581 );
1582 }
1583
1584 #[test]
1585 fn a_failure_with_no_run_id_goes_straight_to_a_human_once_settled() {
1586 let s = open(vec![check("ci/ext", Verdict::Fail, None)]);
1587 assert_eq!(
1588 decide(Some(&s), &st_at(0), 1, 0),
1589 Step::Escalate(Why::StillRed)
1590 );
1591 let s = open(vec![
1592 check("ci/ext", Verdict::Fail, None),
1593 check("x", Verdict::Pending, Some("5")),
1594 ]);
1595 assert_eq!(decide(Some(&s), &st_at(0), 1, 0), Step::Wait);
1596 }
1597
1598 #[test]
1599 fn no_progress_for_the_bounded_time_escalates_and_zero_disables_it() {
1600 let s = open(vec![check("a", Verdict::Pass, Some("1"))]);
1601 assert_eq!(decide(Some(&s), &st_at(0), 3599, 3600), Step::Wait);
1602 assert_eq!(
1603 decide(Some(&s), &st_at(0), 3600, 3600),
1604 Step::Escalate(Why::Stalled)
1605 );
1606 assert_eq!(decide(Some(&s), &st_at(0), 99_999, 0), Step::Wait);
1607 }
1608
1609 #[test]
1610 fn held_and_ignored_stay_quiet_until_the_fingerprint_moves() {
1611 let s = open(vec![check("a", Verdict::Fail, None)]);
1612 let mut st = st_at(0);
1613 st.held = Some(fingerprint(&s));
1614 assert_eq!(decide(Some(&s), &st, 99_999, 60), Step::Wait);
1615 let moved = open(vec![
1616 check("a", Verdict::Pass, None),
1617 check("b", Verdict::Fail, None),
1618 ]);
1619 assert_eq!(
1620 decide(Some(&moved), &st, 99_999, 60),
1621 Step::Escalate(Why::StillRed)
1622 );
1623 st.ignored = true;
1624 assert_eq!(decide(Some(&moved), &st, 99_999, 60), Step::Wait);
1625 }
1626
1627 #[test]
1628 fn observe_restarts_the_clock_only_on_change_and_forgets_reruns_on_a_new_head() {
1629 let mut st = st_at(0);
1630 let a = open(vec![check("a", Verdict::Pending, Some("1"))]);
1631 observe(&mut st, &a, 10);
1632 assert_eq!(st.progress_at, 10);
1633 observe(&mut st, &a, 50);
1634 assert_eq!(st.progress_at, 10);
1635 st.reruns.insert("1".into(), 5);
1636 observe(
1637 &mut st,
1638 &snap(PrLifecycle::Open, "h2", a.checks.clone()),
1639 60,
1640 );
1641 assert!(st.reruns.is_empty());
1642 assert_eq!(st.progress_at, 60);
1643 }
1644
1645 #[test]
1646 fn pr_key_names_owner_repo_and_number() {
1647 assert_eq!(pr_key(URL).as_deref(), Some("o/r#7"));
1648 assert_eq!(pr_key("https://github.com/o/r/issues/7"), None);
1649 assert_eq!(pr_key("nonsense"), None);
1650 }
1651
1652 #[test]
1653 fn notice_wording_does_not_vary_between_polls() {
1654 assert_eq!(rerun_message("o/r#7"), rerun_message("o/r#7"));
1655 assert!(
1656 !human_message("o/r#7")
1657 .chars()
1658 .any(|c| c.is_ascii_digit() && c != '7')
1659 );
1660 }
1661
1662 #[test]
1663 fn the_release_question_is_not_claimed_by_other_machinery() {
1664 let q = Question::new(
1665 String::new(),
1666 crate::bump::NOTICE_NODE.into(),
1667 "release-watch".into(),
1668 "s".into(),
1669 String::new(),
1670 vec![HOLD.into()],
1671 );
1672 assert_eq!(
1674 crate::deputy::kind_of(&q),
1675 Some(crate::deputy::Kind::Release)
1676 );
1677 let n = Notice::warn("release-pr:o/r#7", "m").about([String::new()]);
1678 assert!(!notices::covers(&q, &n));
1679 let mut plain = q.clone();
1681 plain.seat = "bump".into();
1682 assert_eq!(crate::deputy::kind_of(&plain), None);
1683 }
1684
1685 #[derive(Default)]
1686 struct Fake {
1687 snap: Mutex<Option<RollupView>>,
1688 reruns: Mutex<Vec<String>>,
1689 local: Mutex<bool>,
1690 info: Mutex<Option<PrInfo>>,
1691 merges: Mutex<Vec<String>>,
1692 approval: Mutex<Option<bool>>,
1694 merge_fails: Mutex<bool>,
1695 config_fails: Mutex<bool>,
1697 }
1698
1699 impl ReleaseForge for std::sync::Arc<Fake> {
1700 fn list<'a>(&'a self, _: &'a Path) -> Fut<'a, Result<Vec<(String, String)>>> {
1701 Box::pin(async { Ok(vec![("chore/release-v1.0.0".to_owned(), URL.to_owned())]) })
1702 }
1703 fn snapshot<'a>(&'a self, _: &'a Path, _: &'a str) -> Fut<'a, Result<RollupView>> {
1704 let s = self.snap.lock().unwrap().clone();
1705 Box::pin(async move { s.context("unreadable") })
1706 }
1707 fn rerun<'a>(&'a self, _: &'a Path, run: &'a str) -> Fut<'a, Result<()>> {
1708 self.reruns.lock().unwrap().push(run.to_owned());
1709 Box::pin(async { Ok(()) })
1710 }
1711 fn config<'a>(&'a self, _: &'a Path) -> Fut<'a, Result<crate::config::Config>> {
1712 if *self.config_fails.lock().unwrap() {
1713 return Box::pin(async { bail!("unreadable config") });
1714 }
1715 let mut c = crate::config::Config::default();
1716 if *self.local.lock().unwrap() {
1717 c.release.mode = crate::config::ReleaseMode::Local;
1718 c.release.commands = vec!["true".to_owned()];
1719 }
1720 Box::pin(async move { Ok(c) })
1721 }
1722 fn info<'a>(&'a self, _: &'a Path, _: &'a str) -> Fut<'a, Result<PrInfo>> {
1723 let i = self.info.lock().unwrap().clone();
1724 Box::pin(async move { i.context("no info") })
1725 }
1726 fn merge<'a>(&'a self, _: &'a Path, _: &'a str, head: &'a str) -> Fut<'a, Result<bool>> {
1727 self.merges.lock().unwrap().push(head.to_owned());
1728 let fails = *self.merge_fails.lock().unwrap();
1729 Box::pin(async move { if fails { bail!("refused") } else { Ok(true) } })
1730 }
1731 fn land_approval<'a>(&'a self, _: &'a Path) -> Fut<'a, Result<bool>> {
1732 let a = *self.approval.lock().unwrap();
1733 Box::pin(async move { a.context("unreadable config") })
1734 }
1735 }
1736
1737 fn rig() -> (tempfile::TempDir, std::sync::Arc<Fake>, Watcher) {
1738 let dir = tempfile::tempdir().unwrap();
1739 let fake = std::sync::Arc::new(Fake::default());
1740 *fake.approval.lock().unwrap() = Some(true);
1742 let w = Watcher::new(Box::new(fake.clone()), dir.path().to_path_buf());
1743 (dir, fake, w)
1744 }
1745
1746 fn red() -> RollupView {
1747 open(vec![check("win", Verdict::Fail, Some("11"))])
1748 }
1749
1750 #[tokio::test]
1751 async fn reruns_once_survives_a_restart_then_escalates_with_one_question() {
1752 let (dir, fake, w) = rig();
1753 *fake.snap.lock().unwrap() = Some(red());
1754 let repo = PathBuf::from("/nowhere");
1755 let no = || false;
1756 w.lap(std::slice::from_ref(&repo), 3600, 1000, &no).await;
1757 assert_eq!(*fake.reruns.lock().unwrap(), vec!["11".to_owned()]);
1758
1759 let w2 = Watcher::new(Box::new(fake.clone()), dir.path().to_path_buf());
1761 w2.lap(
1762 std::slice::from_ref(&repo),
1763 3600,
1764 1000 + RERUN_GRACE - 1,
1765 &no,
1766 )
1767 .await;
1768 assert_eq!(fake.reruns.lock().unwrap().len(), 1);
1769 assert!(w2.questions().list().is_empty());
1770
1771 w2.lap(
1772 std::slice::from_ref(&repo),
1773 3600,
1774 1000 + RERUN_GRACE + 1,
1775 &no,
1776 )
1777 .await;
1778 w2.lap(
1779 std::slice::from_ref(&repo),
1780 3600,
1781 1000 + RERUN_GRACE + 400,
1782 &no,
1783 )
1784 .await;
1785 assert_eq!(fake.reruns.lock().unwrap().len(), 1);
1786 let qs = w2.questions().list();
1787 assert_eq!(qs.len(), 1, "asked once, not every lap");
1788 assert_eq!(qs[0].node, crate::bump::NOTICE_NODE);
1789 assert!(qs[0].detail.contains("win") && qs[0].detail.contains(URL));
1790 assert_eq!(qs[0].choices, vec![RERUN_AGAIN, HOLD, LEAVE_IT]);
1791 let ns = Notices::at(dir.path().join("notifications")).list();
1792 assert_eq!(ns.len(), 1);
1793 assert_eq!(ns[0].key, "release-pr:o/r#7");
1794 assert_eq!(
1795 ns[0].link,
1796 Some(Link::Url {
1797 url: URL.to_owned(),
1798 })
1799 );
1800 }
1801
1802 async fn escalated() -> (tempfile::TempDir, std::sync::Arc<Fake>, Watcher, String) {
1803 let (dir, fake, w) = rig();
1804 *fake.snap.lock().unwrap() = Some(red());
1805 let repo = PathBuf::from("/nowhere");
1806 let no = || false;
1807 w.lap(std::slice::from_ref(&repo), 3600, 1000, &no).await;
1808 w.lap(&[repo], 3600, 2000, &no).await;
1809 let id = w.questions().list()[0].id.clone();
1810 (dir, fake, w, id)
1811 }
1812
1813 fn answer(w: &Watcher, id: &str, choice: &str) {
1814 w.questions()
1815 .update(id, |q| q.answer(Answer::Choice(choice.to_owned())))
1816 .unwrap();
1817 }
1818
1819 #[tokio::test]
1820 async fn legacy_rerun_again_reruns_exactly_once_more() {
1821 let (_d, fake, w, id) = escalated().await;
1822 w.questions()
1823 .update(&id, |q| {
1824 q.actions.clear();
1825 Ok(())
1826 })
1827 .unwrap();
1828 answer(&w, &id, RERUN_AGAIN);
1829 let repo = PathBuf::from("/nowhere");
1830 let no = || false;
1831 w.lap(std::slice::from_ref(&repo), 3600, 3000, &no).await;
1832 w.lap(&[repo], 3600, 3001, &no).await;
1833 assert_eq!(fake.reruns.lock().unwrap().len(), 2);
1834 }
1835
1836 #[tokio::test]
1837 async fn typed_rerun_is_left_to_the_daemon_instead_of_the_watcher() {
1838 let (_d, fake, w, id) = escalated().await;
1839 let q = w.questions().get(&id).unwrap();
1840 assert!(
1841 matches!(q.actions.get(RERUN_AGAIN), Some(crate::ask::ChoiceAction::RerunChecks { head, runs, .. })
1842 if head == "h1" && runs == &["11"])
1843 );
1844 answer(&w, &id, RERUN_AGAIN);
1845 w.lap(&[PathBuf::from("/nowhere")], 3600, 3000, &|| false)
1846 .await;
1847 assert_eq!(
1848 fake.reruns.lock().unwrap().len(),
1849 1,
1850 "only the earlier automatic rerun"
1851 );
1852 }
1853
1854 #[test]
1855 fn no_failed_workflow_means_no_rerun_choice() {
1856 let snap = open(vec![check("external", Verdict::Fail, None)]);
1857 assert_eq!(maintenance_choices(&snap), vec![HOLD, LEAVE_IT]);
1858 }
1859
1860 #[tokio::test]
1861 async fn hold_and_silence_do_not_reask_and_leave_it_dismisses() {
1862 let (d, fake, w, id) = escalated().await;
1863 answer(&w, &id, HOLD);
1864 let repo = PathBuf::from("/nowhere");
1865 let no = || false;
1866 for t in [3000, 90_000, 200_000] {
1867 w.lap(std::slice::from_ref(&repo), 3600, t, &no).await;
1868 }
1869 assert_eq!(w.questions().list().len(), 1, "held: no second question");
1870 assert_eq!(fake.reruns.lock().unwrap().len(), 1);
1871
1872 let (d2, _f2, w2, id2) = escalated().await;
1873 answer(&w2, &id2, LEAVE_IT);
1874 w2.lap(std::slice::from_ref(&repo), 3600, 3000, &no).await;
1875 let ns = Notices::at(d2.path().join("notifications")).list();
1876 assert!(ns.is_empty(), "dismissed notices are hidden");
1877 drop(d);
1878 }
1879
1880 fn with_deputy(w: &Watcher, id: &str, home: &Path) -> String {
1882 let seat = crate::agent::SeatState::new(&crate::ask::deputy_seat_key(id), "a", 1);
1883 let key = seat.key.clone();
1884 let brief = deputy_brief(&w.questions().get(id).unwrap(), home);
1885 w.questions()
1886 .update(id, |q| {
1887 let mut d = crate::ask::Deputy::new(brief);
1888 d.seat = Some(seat);
1889 q.deputy = Some(d);
1890 Ok(())
1891 })
1892 .unwrap();
1893 key
1894 }
1895
1896 #[tokio::test]
1897 async fn the_brief_names_the_pull_request_and_what_leave_it_really_does() {
1898 let (d, _f, w, id) = escalated().await;
1899 let q = w.questions().get(&id).unwrap();
1900 let b = deputy_brief(&q, d.path());
1901 assert!(b.contains(URL), "{b}");
1902 assert!(
1903 b.contains("`leave it`") && b.contains("does NOT close"),
1904 "{b}"
1905 );
1906 assert!(b.contains("`rerun again`") && b.contains("`hold`"), "{b}");
1907 assert!(!b.contains("`merge`"), "no merge on an escalation: {b}");
1908
1909 let empty = tempfile::tempdir().unwrap();
1911 let b = deputy_brief(&q, empty.path());
1912 assert!(b.contains("could not be found") && !b.contains(URL), "{b}");
1913 }
1914
1915 #[tokio::test]
1916 async fn a_settled_leave_it_is_applied_once_by_the_watcher_and_closes_nothing() {
1917 let (d, fake, w, id) = escalated().await;
1918 let seat = with_deputy(&w, &id, d.path());
1919 let say = "クローズしていいよ。private repo だから、何回やっても失敗しちゃうから";
1920 w.questions().update(&id, |q| q.say(say)).unwrap();
1921 w.questions()
1922 .update(&id, |q| {
1923 q.settle_by_deputy(&seat, LEAVE_IT, "クローズしていいよ", None)
1924 })
1925 .unwrap();
1926 let q = w.questions().get(&id).unwrap();
1927 assert_eq!(q.answer, Some(Answer::Choice(LEAVE_IT.to_owned())));
1928
1929 let repo = PathBuf::from("/nowhere");
1930 let no = || false;
1931 for t in [3000, 3100] {
1932 w.lap(std::slice::from_ref(&repo), 3600, t, &no).await;
1933 }
1934 let st = w.stored().pop().unwrap();
1935 assert!(st.ignored, "watching stopped");
1936 assert_eq!(st.applied, vec![id.clone()], "applied exactly once");
1937 assert!(
1938 Notices::at(d.path().join("notifications"))
1939 .list()
1940 .is_empty()
1941 );
1942 assert_eq!(fake.reruns.lock().unwrap().len(), 1, "no extra rerun");
1943 assert_eq!(w.questions().list().len(), 1, "no second question");
1944 }
1945
1946 #[tokio::test]
1947 async fn the_task_of_a_release_question_comes_from_the_watch_record() {
1948 let (d, _f, w, id) = escalated().await;
1949 let q = w.questions().get(&id).unwrap();
1950 let queue = crate::queue::Queue::at(d.path().join("queue"));
1951 assert!(
1952 task_of_question(d.path(), &q, &queue).is_none(),
1953 "no run known"
1954 );
1955 assert!(task_of_question(d.path(), &q, &queue).is_none());
1956 let mut st = w.stored().pop().unwrap();
1957 st.run = Some("run-1".into());
1958 w.save("o/r#7", &st);
1959 assert!(task_of_question(d.path(), &q, &queue).is_none());
1961 let mut t = crate::queue::Task::new(
1962 "t".into(),
1963 "i".into(),
1964 PathBuf::from("/nowhere"),
1965 crate::queue::Source::Human,
1966 );
1967 t.runs.push("run-1".into());
1968 queue.put(&mut t).unwrap();
1969 assert_eq!(task_of_question(d.path(), &q, &queue).unwrap().id, t.id);
1970 }
1971
1972 #[tokio::test]
1973 async fn merged_clears_the_notice_the_question_and_the_record() {
1974 let (d, fake, w, _id) = escalated().await;
1975 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Merged, "h1", vec![]));
1976 let repo = PathBuf::from("/nowhere");
1977 w.lap(&[repo], 3600, 5000, &(|| false)).await;
1978 assert!(
1979 Notices::at(d.path().join("notifications"))
1980 .list()
1981 .is_empty()
1982 );
1983 assert!(w.questions().list().iter().all(|q| !q.status.open()));
1984 assert!(w.stored().is_empty());
1985 }
1986
1987 #[tokio::test]
1988 async fn an_unreadable_forge_changes_nothing() {
1989 let (d, fake, w) = rig();
1990 *fake.snap.lock().unwrap() = None;
1991 w.lap(&[PathBuf::from("/nowhere")], 60, 99_999, &(|| false))
1992 .await;
1993 assert!(fake.reruns.lock().unwrap().is_empty());
1994 assert!(w.questions().list().is_empty());
1995 assert!(!d.path().join("release-watch").exists());
1996 }
1997
1998 #[tokio::test]
1999 async fn no_rerun_when_the_record_cannot_be_saved() {
2000 let (d, fake, w) = rig();
2001 *fake.snap.lock().unwrap() = Some(red());
2002 std::fs::write(d.path().join("release-watch"), "x").unwrap();
2004 w.lap(&[PathBuf::from("/nowhere")], 3600, 1000, &(|| false))
2005 .await;
2006 assert!(fake.reruns.lock().unwrap().is_empty());
2007 }
2008
2009 #[tokio::test]
2010 async fn a_park_stops_the_lap_before_any_call() {
2011 let (_d, fake, w) = rig();
2012 *fake.snap.lock().unwrap() = Some(red());
2013 w.lap(&[PathBuf::from("/nowhere")], 60, 1000, &(|| true))
2014 .await;
2015 assert!(fake.reruns.lock().unwrap().is_empty());
2016 }
2017
2018 fn local_st(asked: Option<&str>, held: Option<&str>) -> WatchState {
2021 WatchState {
2022 asked_head: asked.map(str::to_owned),
2023 held_head: held.map(str::to_owned),
2024 ..WatchState::default()
2025 }
2026 }
2027
2028 #[test]
2029 fn local_decisions_never_wait_on_ci_and_bind_approval_to_the_head() {
2030 use Approved::*;
2031 let none = local_st(None, None);
2032 assert_eq!(decide_local("h1", &none, NoQuestion, true), LocalStep::Ask);
2033 assert_eq!(decide_local("h1", &none, Open, true), LocalStep::Wait);
2034 let asked = local_st(Some("h1"), None);
2035 assert_eq!(
2036 decide_local("h1", &asked, Merge, true),
2037 LocalStep::Merge("h1".to_owned())
2038 );
2039 assert_eq!(
2040 decide_local("h1", &asked, Hold, true),
2041 LocalStep::Hold("h1".to_owned())
2042 );
2043 assert_eq!(decide_local("h2", &asked, Merge, true), LocalStep::Ask);
2045 assert_eq!(decide_local("h2", &asked, Hold, true), LocalStep::Ask);
2046 let held = local_st(Some("h1"), Some("h1"));
2048 assert_eq!(decide_local("h1", &held, NoQuestion, true), LocalStep::Wait);
2049 assert_eq!(decide_local("h2", &held, NoQuestion, true), LocalStep::Ask);
2050 let mut ign = local_st(None, None);
2051 ign.ignored = true;
2052 assert_eq!(decide_local("h1", &ign, NoQuestion, true), LocalStep::Wait);
2053 }
2054
2055 #[test]
2056 fn without_land_approval_an_unasked_head_merges_but_stops_stay_stopped() {
2057 use Approved::*;
2058 let none = local_st(None, None);
2059 assert_eq!(
2060 decide_local("h1", &none, NoQuestion, false),
2061 LocalStep::Merge("h1".to_owned())
2062 );
2063 assert_eq!(decide_local("h1", &none, Open, false), LocalStep::Wait);
2065 let held = local_st(Some("h1"), Some("h1"));
2066 assert_eq!(
2067 decide_local("h1", &held, NoQuestion, false),
2068 LocalStep::Wait
2069 );
2070 assert_eq!(
2071 decide_local("h2", &held, NoQuestion, false),
2072 LocalStep::Merge("h2".to_owned())
2073 );
2074 let mut ign = local_st(None, None);
2075 ign.ignored = true;
2076 assert_eq!(decide_local("h1", &ign, NoQuestion, false), LocalStep::Wait);
2077 let asked = local_st(Some("h1"), None);
2079 assert_eq!(
2080 decide_local("h1", &asked, Hold, false),
2081 LocalStep::Hold("h1".to_owned())
2082 );
2083 }
2084
2085 #[tokio::test]
2086 async fn a_registered_local_pr_still_asks_but_never_merges_while_the_config_is_unreadable() {
2087 let (dir, fake, w) = rig();
2088 *fake.config_fails.lock().unwrap() = true;
2089 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Open, "h1", vec![]));
2090 let repo = PathBuf::from("/nowhere");
2091 let no = || false;
2092 let pr = pr_key(URL).unwrap();
2093 register(dir.path(), &repo, URL, "run1");
2094 assert!(w.load(&pr).local);
2096 w.lap(std::slice::from_ref(&repo), 60, 1, &no).await;
2097 w.lap(std::slice::from_ref(&repo), 60, 2, &no).await;
2098 assert!(fake.merges.lock().unwrap().is_empty());
2099 let qs = w.questions().list();
2100 assert_eq!(qs.len(), 1);
2101 assert_eq!(qs[0].choices, vec![land::APPROVE, land::HOLD]);
2102 answer(&w, &qs[0].id, land::APPROVE);
2104 w.lap(std::slice::from_ref(&repo), 60, 3, &no).await;
2105 assert!(fake.merges.lock().unwrap().is_empty());
2106 assert_eq!(w.load(&pr).question.as_deref(), Some(qs[0].id.as_str()));
2107 *fake.config_fails.lock().unwrap() = false;
2109 *fake.local.lock().unwrap() = true;
2110 w.lap(std::slice::from_ref(&repo), 60, 4, &no).await;
2111 assert_eq!(*fake.merges.lock().unwrap(), vec!["h1".to_owned()]);
2112 }
2113
2114 #[tokio::test]
2115 async fn a_local_record_written_before_the_flag_existed_is_still_local() {
2116 let (_d, fake, w) = rig();
2117 *fake.config_fails.lock().unwrap() = true;
2118 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Open, "h1", vec![]));
2119 let repo = PathBuf::from("/nowhere");
2120 let no = || false;
2121 let pr = pr_key(URL).unwrap();
2122 let old = WatchState {
2123 repo: repo.to_string_lossy().into_owned(),
2124 url: URL.to_owned(),
2125 run: Some("run1".to_owned()),
2126 ..WatchState::default()
2127 };
2128 assert!(!old.local);
2129 w.save(&pr, &old);
2130 w.lap(std::slice::from_ref(&repo), 60, 1, &no).await;
2131 assert!(fake.merges.lock().unwrap().is_empty());
2132 let qs = w.questions().list();
2133 assert_eq!(qs.len(), 1);
2134 assert_eq!(qs[0].choices, vec![land::APPROVE, land::HOLD]);
2135 }
2136
2137 #[tokio::test]
2138 async fn an_unregistered_pr_is_an_actions_release_when_the_config_is_unreadable() {
2139 let (_d, fake, w) = rig();
2140 *fake.config_fails.lock().unwrap() = true;
2141 *fake.snap.lock().unwrap() = Some(red());
2142 let repo = PathBuf::from("/nowhere");
2143 let no = || false;
2144 w.lap(std::slice::from_ref(&repo), 3600, 1000, &no).await;
2145 assert_eq!(*fake.reruns.lock().unwrap(), vec!["11".to_owned()]);
2146 }
2147
2148 #[tokio::test]
2149 async fn a_merged_local_pr_waits_with_its_record_while_the_config_is_unreadable() {
2150 let (dir, fake, w) = rig();
2151 *fake.config_fails.lock().unwrap() = true;
2152 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Merged, "h1", vec![]));
2153 let repo = PathBuf::from("/nowhere");
2154 let no = || false;
2155 let pr = pr_key(URL).unwrap();
2156 register(dir.path(), &repo, URL, "run1");
2157 w.lap(std::slice::from_ref(&repo), 60, 1, &no).await;
2158 assert!(w.state_path(&pr).exists(), "the record is kept");
2159 }
2160
2161 #[tokio::test]
2162 async fn land_approval_off_merges_the_observed_head_without_a_question() {
2163 let (_d, fake, w) = rig();
2164 *fake.local.lock().unwrap() = true;
2165 *fake.approval.lock().unwrap() = Some(false);
2166 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Open, "h1", vec![]));
2167 let repo = PathBuf::from("/nowhere");
2168 let no = || false;
2169 w.lap(std::slice::from_ref(&repo), 60, 1, &no).await;
2170 assert_eq!(*fake.merges.lock().unwrap(), vec!["h1".to_owned()]);
2171 assert!(w.questions().list().is_empty(), "no approval question");
2172 }
2173
2174 #[tokio::test]
2175 async fn land_approval_on_or_unreadable_still_asks_and_never_merges() {
2176 for approval in [Some(true), None] {
2177 let (_d, fake, w) = rig();
2178 *fake.local.lock().unwrap() = true;
2179 *fake.approval.lock().unwrap() = approval;
2180 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Open, "h1", vec![]));
2181 let repo = PathBuf::from("/nowhere");
2182 let no = || false;
2183 w.lap(std::slice::from_ref(&repo), 60, 1, &no).await;
2184 w.lap(std::slice::from_ref(&repo), 60, 2, &no).await;
2185 assert!(fake.merges.lock().unwrap().is_empty(), "silence is a hold");
2186 let qs = w.questions().list();
2187 assert_eq!(qs.len(), 1);
2188 assert_eq!(qs[0].choices, vec![land::APPROVE, land::HOLD]);
2189 }
2190 }
2191
2192 #[tokio::test]
2193 async fn land_approval_off_does_not_merge_on_an_unreadable_forge_or_retry_a_refusal() {
2194 let (_d, fake, w) = rig();
2195 *fake.local.lock().unwrap() = true;
2196 *fake.approval.lock().unwrap() = Some(false);
2197 let repo = PathBuf::from("/nowhere");
2198 let no = || false;
2199 *fake.snap.lock().unwrap() = None;
2201 w.lap(std::slice::from_ref(&repo), 60, 1, &no).await;
2202 assert!(fake.merges.lock().unwrap().is_empty());
2203 *fake.merge_fails.lock().unwrap() = true;
2205 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Open, "h1", vec![]));
2206 w.lap(std::slice::from_ref(&repo), 60, 2, &no).await;
2207 w.lap(std::slice::from_ref(&repo), 60, 3, &no).await;
2208 assert_eq!(fake.merges.lock().unwrap().len(), 1);
2209 assert!(w.questions().list().is_empty());
2210 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Open, "h2", vec![]));
2212 w.lap(std::slice::from_ref(&repo), 60, 4, &no).await;
2213 assert_eq!(
2214 *fake.merges.lock().unwrap(),
2215 vec!["h1".to_owned(), "h2".to_owned()]
2216 );
2217 }
2218
2219 #[test]
2220 fn pr_info_is_read_from_gh_json() {
2221 let i = parse_info(
2222 r#"{"headRefName":"chore/release-v1.2.3","title":"chore: release v1.2.3","mergeCommit":{"oid":"abc"}}"#,
2223 )
2224 .unwrap();
2225 assert_eq!(i.branch, "chore/release-v1.2.3");
2226 assert_eq!(i.merge_commit.as_deref(), Some("abc"));
2227 let open = parse_info(r#"{"headRefName":"b","title":"t","mergeCommit":null}"#).unwrap();
2228 assert_eq!(open.merge_commit, None);
2229 }
2230
2231 #[tokio::test]
2232 async fn a_local_release_asks_once_without_ci_reruns_or_stall_escalation() {
2233 let (_d, fake, w) = rig();
2234 *fake.local.lock().unwrap() = true;
2235 *fake.snap.lock().unwrap() = Some(red());
2238 let repo = PathBuf::from("/nowhere");
2239 let no = || false;
2240 w.lap(std::slice::from_ref(&repo), 60, 1_000_000, &no).await;
2241 w.lap(std::slice::from_ref(&repo), 60, 2_000_000, &no).await;
2242 assert!(fake.reruns.lock().unwrap().is_empty());
2243 let qs = w.questions().list();
2244 assert_eq!(qs.len(), 1, "one approval question, not one per lap");
2245 assert_eq!(qs[0].choices, vec![land::APPROVE, land::HOLD]);
2246 assert!(fake.merges.lock().unwrap().is_empty(), "silence is a hold");
2247 }
2248
2249 #[tokio::test]
2250 async fn merge_is_pinned_to_the_approved_head_and_a_moved_head_asks_again() {
2251 let (_d, fake, w) = rig();
2252 *fake.local.lock().unwrap() = true;
2253 *fake.snap.lock().unwrap() = Some(open(vec![]));
2254 let repo = PathBuf::from("/nowhere");
2255 let no = || false;
2256 w.lap(std::slice::from_ref(&repo), 60, 1, &no).await;
2257 let original = &w.questions().list()[0];
2258 assert_eq!(original.merge_target.as_ref().unwrap().head, "h1");
2259 let id = original.id.clone();
2260 w.questions()
2261 .update(&id, |q| {
2262 q.merge_target = None;
2263 Ok(())
2264 })
2265 .unwrap();
2266 assert_eq!(
2267 w.questions()
2268 .get(&id)
2269 .unwrap()
2270 .merge_target
2271 .as_ref()
2272 .unwrap()
2273 .head,
2274 "h1",
2275 "legacy binding comes from the matching persisted watch record"
2276 );
2277 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Open, "h2", vec![]));
2279 answer(&w, &id, land::APPROVE);
2280 w.lap(std::slice::from_ref(&repo), 60, 2, &no).await;
2281 assert!(fake.merges.lock().unwrap().is_empty());
2282 assert_eq!(w.questions().list().len(), 2, "asked again about h2");
2283 let id2 = w
2285 .questions()
2286 .list()
2287 .into_iter()
2288 .find(|q| q.status.open())
2289 .unwrap()
2290 .id;
2291 answer(&w, &id2, land::APPROVE);
2292 w.lap(std::slice::from_ref(&repo), 60, 3, &no).await;
2293 assert_eq!(*fake.merges.lock().unwrap(), vec!["h2".to_owned()]);
2294 }
2295
2296 #[tokio::test]
2297 async fn a_failed_release_holds_with_one_notice_and_one_question_and_never_retries() {
2298 let (d, fake, w) = rig();
2299 *fake.local.lock().unwrap() = true;
2300 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Merged, "h1", vec![]));
2301 *fake.info.lock().unwrap() = Some(PrInfo {
2302 branch: "chore/release-v1.0.0".to_owned(),
2303 merge_commit: Some("deadbeef".to_owned()),
2304 title: "chore: release v1.0.0".to_owned(),
2305 });
2306 let repo = d.path().join("nowhere");
2308 let no = || false;
2309 w.lap(std::slice::from_ref(&repo), 60, 1, &no).await;
2310 let st = w.load("o/r#7");
2311 let job = st.job.expect("the job is recorded");
2312 assert!(job.failed.is_some() && !job.tag_done && !job.finished);
2313 let qs = w.questions().list();
2314 assert_eq!(qs.len(), 1);
2315 assert_eq!(qs[0].choices, vec![RETRY, LEAVE_IT]);
2316 w.lap(std::slice::from_ref(&repo), 60, 2, &no).await;
2318 assert_eq!(w.questions().list().len(), 1);
2319 let ns = Notices::at(d.path().join("notifications")).list();
2320 assert_eq!(ns.len(), 1);
2321 assert_eq!(
2322 ns[0].link,
2323 Some(Link::Url {
2324 url: URL.to_owned(),
2325 })
2326 );
2327 }
2328
2329 #[tokio::test]
2330 async fn an_escalated_pull_request_records_the_title_version_as_acceptable() {
2331 let (d, fake, w) = rig();
2332 *fake.local.lock().unwrap() = true;
2333 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Merged, "h1", vec![]));
2334 *fake.info.lock().unwrap() = Some(PrInfo {
2335 branch: "chore/release-v0.1.4".to_owned(),
2336 merge_commit: Some("deadbeef".to_owned()),
2337 title: "chore: release v0.2.0 (minor bump)".to_owned(),
2338 });
2339 let repo = d.path().join("nowhere");
2340 w.lap(std::slice::from_ref(&repo), 60, 1, &(|| false)).await;
2341 let job = w.load("o/r#7").job.expect("the job is recorded");
2342 assert_eq!(job.version, "0.1.4");
2343 assert_eq!(job.accepted, vec!["0.2.0".to_owned()]);
2344 }
2345
2346 #[tokio::test]
2347 async fn a_failed_release_holds_the_task_whose_run_opened_the_pr() {
2348 let (d, fake, w) = rig();
2349 *fake.local.lock().unwrap() = true;
2350 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Merged, "h1", vec![]));
2351 *fake.info.lock().unwrap() = Some(PrInfo {
2352 branch: "chore/release-v1.0.0".to_owned(),
2353 merge_commit: Some("deadbeef".to_owned()),
2354 title: "t".to_owned(),
2355 });
2356 let repo = d.path().join("nowhere");
2357 let q = crate::queue::Queue::at(d.path().join("queue"));
2358 let mut t = crate::queue::Task::new(
2359 "t".to_owned(),
2360 "i".to_owned(),
2361 repo.clone(),
2362 crate::queue::Source::Human,
2363 );
2364 t.runs.push("run1".to_owned());
2365 t.status = crate::queue::TaskStatus::Done;
2366 q.put(&mut t).unwrap();
2367 register(d.path(), &repo, URL, "run1");
2368 w.lap(std::slice::from_ref(&repo), 60, 1, &(|| false)).await;
2369 let held = q.get(&t.id).unwrap();
2370 assert_eq!(held.status, crate::queue::TaskStatus::Held);
2371 assert!(
2372 held.hold_reason
2373 .unwrap_or_default()
2374 .contains("release v1.0.0")
2375 );
2376 }
2377
2378 #[tokio::test]
2379 async fn unhold_gives_the_task_back_only_when_the_hold_is_ours() {
2380 let (d, _fake, w) = rig();
2381 let q = crate::queue::Queue::at(d.path().join("queue"));
2382 let mut t = crate::queue::Task::new(
2383 "t".to_owned(),
2384 "i".to_owned(),
2385 PathBuf::from("/r"),
2386 crate::queue::Source::Human,
2387 );
2388 t.runs.push("run1".to_owned());
2389 t.status = crate::queue::TaskStatus::Done;
2390 q.put(&mut t).unwrap();
2391 let mut st = WatchState {
2392 run: Some("run1".to_owned()),
2393 ..WatchState::default()
2394 };
2395 w.hold_task(&mut st, "failed");
2396 assert_eq!(q.get(&t.id).unwrap().status, crate::queue::TaskStatus::Held);
2397 w.hold_task(&mut st, "failed again");
2399 assert!(w.unhold_task(&mut st));
2400 assert_eq!(q.get(&t.id).unwrap().status, crate::queue::TaskStatus::Done);
2401 assert!(st.held_task.is_none());
2402
2403 let mut h = q.get(&t.id).unwrap();
2405 st.held_task = Some(h.id.clone());
2406 h.hold_manual(Some("mine".to_owned()));
2407 q.put(&mut h).unwrap();
2408 assert!(w.unhold_task(&mut st));
2409 assert_eq!(q.get(&t.id).unwrap().status, crate::queue::TaskStatus::Held);
2410 }
2411
2412 #[tokio::test]
2413 async fn a_restart_after_the_failure_was_saved_still_holds_the_task() {
2414 let (d, fake, w) = rig();
2415 *fake.local.lock().unwrap() = true;
2416 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Merged, "h1", vec![]));
2417 let repo = d.path().join("nowhere");
2418 let q = crate::queue::Queue::at(d.path().join("queue"));
2419 let mut t = crate::queue::Task::new(
2420 "t".to_owned(),
2421 "i".to_owned(),
2422 repo.clone(),
2423 crate::queue::Source::Human,
2424 );
2425 t.runs.push("run1".to_owned());
2426 t.status = crate::queue::TaskStatus::Done;
2427 q.put(&mut t).unwrap();
2428 let mut job = Job::new("1.0.0", URL, "deadbeef");
2430 job.failed = Some("command 1 exited 3".to_owned());
2431 let st = WatchState {
2432 repo: repo.to_string_lossy().into_owned(),
2433 url: URL.to_owned(),
2434 run: Some("run1".to_owned()),
2435 job: Some(job),
2436 ..WatchState::default()
2437 };
2438 w.save("o/r#7", &st);
2439 w.lap(std::slice::from_ref(&repo), 60, 1, &(|| false)).await;
2440 assert_eq!(q.get(&t.id).unwrap().status, crate::queue::TaskStatus::Held);
2441 }
2442
2443 #[tokio::test]
2444 async fn a_restart_after_the_job_finished_still_gives_the_task_back() {
2445 let (d, fake, w) = rig();
2446 *fake.local.lock().unwrap() = true;
2447 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Merged, "h1", vec![]));
2448 let repo = d.path().join("nowhere");
2449 let q = crate::queue::Queue::at(d.path().join("queue"));
2450 let mut t = crate::queue::Task::new(
2451 "t".to_owned(),
2452 "i".to_owned(),
2453 repo.clone(),
2454 crate::queue::Source::Human,
2455 );
2456 t.runs.push("run1".to_owned());
2457 t.hold_machine(Some(format!("{HOLD_PREFIX}release v1.0.0 failed")));
2458 q.put(&mut t).unwrap();
2459 let mut job = Job::new("1.0.0", URL, "deadbeef");
2461 job.finished = true;
2462 let st = WatchState {
2463 repo: repo.to_string_lossy().into_owned(),
2464 url: URL.to_owned(),
2465 run: Some("run1".to_owned()),
2466 job: Some(job),
2467 held_task: Some(t.id.clone()),
2468 ..WatchState::default()
2469 };
2470 w.save("o/r#7", &st);
2471 w.lap(std::slice::from_ref(&repo), 60, 1, &(|| false)).await;
2472 assert_eq!(q.get(&t.id).unwrap().status, crate::queue::TaskStatus::Done);
2473 assert!(!w.state_path("o/r#7").exists());
2474 }
2475
2476 #[tokio::test]
2477 async fn a_pull_request_registered_at_open_is_picked_up_even_if_unlisted() {
2478 let (d, _fake, w) = rig();
2479 register(d.path(), Path::new("/r"), URL, "run1");
2480 let st = w.load("o/r#7");
2481 assert_eq!(st.url, URL);
2482 assert_eq!(st.repo, "/r");
2483 let mut live = st.clone();
2485 live.head = "keep".to_owned();
2486 w.save("o/r#7", &live);
2487 register(d.path(), Path::new("/r"), URL, "run1");
2488 assert_eq!(w.load("o/r#7").head, "keep");
2489 }
2490
2491 #[tokio::test]
2492 async fn a_finished_release_is_kept_on_the_run_and_a_missing_run_still_completes() {
2493 let (d, fake, w) = rig();
2494 *fake.local.lock().unwrap() = true;
2495 *fake.snap.lock().unwrap() = Some(snap(PrLifecycle::Merged, "h1", vec![]));
2496 let repo = d.path().join("nowhere");
2497 let mut run = RunState::new(
2498 repo.clone(),
2499 "main".to_owned(),
2500 "0123456789abcdef".to_owned(),
2501 "t".to_owned(),
2502 crate::config::Config::default(),
2503 );
2504 run.id = "run1".to_owned();
2505 run.save_under(d.path()).unwrap();
2506 let mut job = Job::new("1.0.0", URL, "deadbeef");
2507 job.finished = true;
2508 job.log.push(release_local::StepLog {
2509 name: "cmd".to_owned(),
2510 code: Some(0),
2511 tail: "ok".to_owned(),
2512 output: None,
2513 });
2514 let mk = |run: &str| WatchState {
2515 repo: repo.to_string_lossy().into_owned(),
2516 url: URL.to_owned(),
2517 run: Some(run.to_owned()),
2518 job: Some(job.clone()),
2519 ..WatchState::default()
2520 };
2521 w.save("o/r#7", &mk("run1"));
2522 w.lap(std::slice::from_ref(&repo), 60, 1, &(|| false)).await;
2523 assert!(!w.state_path("o/r#7").exists());
2524 let kept = RunState::load_under("run1", d.path()).unwrap();
2525 assert_eq!(kept.release_bump.unwrap().release, Some(job.clone()));
2526
2527 w.save("o/r#7", &mk("gone"));
2529 w.lap(std::slice::from_ref(&repo), 60, 1, &(|| false)).await;
2530 assert!(!w.state_path("o/r#7").exists());
2531 }
2532
2533 #[tokio::test]
2534 async fn raise_released_attaches_url_link() {
2535 let (d, _fake, w) = rig();
2536 let job = Job::new("1.0.0", URL, "deadbeef");
2537 w.raise_released("o/r#7", URL, &job);
2538 let ns = Notices::at(d.path().join("notifications")).list();
2539 assert_eq!(ns.len(), 1);
2540 assert_eq!(ns[0].key, "release-done:o/r#7");
2541 assert_eq!(
2542 ns[0].link,
2543 Some(Link::Url {
2544 url: URL.to_owned(),
2545 })
2546 );
2547 }
2548}