Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add retries to GitHub land API call #168

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 18 additions & 21 deletions spr/src/commands/land.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use std::{io::Write, process::Stdio, time::Duration};
use crate::{
error::{Error, Result, ResultExt},
github::{PullRequestState, PullRequestUpdate, ReviewStatus},
message::build_github_body_for_merging,
output::{output, write_commit_title},
utils::do_with_retry,
utils::run_command,
};

Expand Down Expand Up @@ -303,26 +303,23 @@ pub async fn land(
// used a base branch with this Pull Request or not. We have made sure the
// target of the Pull Request is set to the master branch. So let GitHub do
// the merge now!
octocrab::instance()
.pulls(&config.owner, &config.repo)
.merge(pull_request_number)
.method(octocrab::params::pulls::MergeMethod::Squash)
.title(pull_request.title)
.message(build_github_body_for_merging(&pull_request.sections))
.sha(format!("{}", pr_head_oid))
.send()
.await
.convert()
.and_then(|merge| {
if merge.merged {
Ok(merge)
} else {
Err(Error::new(formatdoc!(
"GitHub Pull Request merge failed: {}",
merge.message.unwrap_or_default()
)))
}
})

// Sometimes it takes a couple of tries to land a PR. Let's try a few times.
do_with_retry(
|| {
gh.land_pull_request(
pull_request_number,
&pull_request,
pr_head_oid,
)
},
5,
|_| {
output("❌", "Landing GitHub Pull Request failed, will retry in 1 second")
},
Duration::from_secs(1),
)
.await
}
Err(err) => Err(err),
};
Expand Down
32 changes: 31 additions & 1 deletion spr/src/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
*/

use graphql_client::{GraphQLQuery, Response};
use indoc::formatdoc;
use serde::Deserialize;

use crate::{
error::{Error, Result, ResultExt},
git::Git,
message::{
build_github_body, parse_message, MessageSection, MessageSectionsMap,
build_github_body, build_github_body_for_merging, parse_message,
MessageSection, MessageSectionsMap,
},
};
use std::collections::{HashMap, HashSet};
Expand Down Expand Up @@ -436,6 +438,34 @@ impl GitHub {
.and_then(|sha| git2::Oid::from_str(&sha.oid).ok()),
})
}

pub async fn land_pull_request(
&self,
pull_request_number: u64,
pull_request: &PullRequest,
pull_request_head_oid: git2::Oid,
) -> Result<octocrab::models::pulls::Merge> {
octocrab::instance()
.pulls(&self.config.owner, &self.config.repo)
.merge(pull_request_number)
.method(octocrab::params::pulls::MergeMethod::Squash)
.title(pull_request.title.clone())
.message(build_github_body_for_merging(&pull_request.sections))
.sha(format!("{}", pull_request_head_oid))
.send()
.await
.convert()
.and_then(|merge| {
if merge.merged {
Ok(merge)
} else {
Err(Error::new(formatdoc!(
"GitHub Pull Request merge failed: {}",
merge.message.unwrap_or_default()
)))
}
})
}
}

#[derive(Debug, Clone)]
Expand Down
27 changes: 26 additions & 1 deletion spr/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

use crate::error::{Error, Result};

use std::{io::Write, process::Stdio};
use std::{future::Future, io::Write, process::Stdio, time::Duration};
use unicode_normalization::UnicodeNormalization;

pub fn slugify(s: &str) -> String {
Expand Down Expand Up @@ -58,6 +58,31 @@ pub async fn run_command(cmd: &mut tokio::process::Command) -> Result<()> {
Ok(())
}

pub async fn do_with_retry<F, Fut, FOut, H>(
f: F,
attempts: u64,
on_error: H,
sleep_time: Duration,
) -> Result<FOut>
where
F: Fn() -> Fut,
Fut: Future<Output = Result<FOut>>,
H: Fn(&Error) -> Result<()>,
{
let mut last_error = None;
for _ in 0..attempts {
match f().await {
Ok(val) => return Ok(val),
Err(err) => {
on_error(&err)?;
tokio::time::sleep(sleep_time).await;
last_error = Some(err);
}
}
}
Err(last_error.unwrap())
}

#[cfg(test)]
mod tests {
// Note this useful idiom: importing names from outer (for mod tests) scope.
Expand Down
Loading