Skip to content

Commit

Permalink
fix: Attempt Chat API request max 3 times
Browse files Browse the repository at this point in the history
  • Loading branch information
akash1810 committed Nov 5, 2024
1 parent 5ea82ec commit 1b3c1e3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
24 changes: 16 additions & 8 deletions src/google.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@ impl GoogleChatMessage {
Ok(updated_url.as_str().to_string())
}

pub async fn send(self, webhook_url: &str, thread_key: &str) -> Result<GoogleChatMessage> {
pub async fn send(
self,
webhook_url: &str,
thread_key: &str,
attempt: i32,
) -> Result<GoogleChatMessage> {
let max_attempts = 3;
let url = GoogleChatMessage::build_webhook_url(webhook_url, thread_key)?;

let response = reqwest::Client::new()
Expand All @@ -47,22 +53,24 @@ impl GoogleChatMessage {
if response
.status()
.eq(&reqwest::StatusCode::TOO_MANY_REQUESTS)
&& attempt < max_attempts
{
/*
Sleep for 1.5 seconds to avoid rate limiting, at 60 requests per minute.
See https://developers.google.com/workspace/chat/limits
*/
info!(
"Received {} response. Sleeping for 1.5 seconds before retrying",
response.status()
"Received {} response. Sleeping for 1.5 seconds before retrying (attempt {})",
response.status(),
attempt
);
tokio::time::sleep(time::Duration::from_millis(1500)).await;
Box::pin(self.send(webhook_url, thread_key)).await
Box::pin(self.send(webhook_url, thread_key, attempt + 1)).await
} else {
let response_text = response
.text()
.await
.context(format!("Failed to get response from: {}", &webhook_url))?;
let response_text = response.text().await.context(format!(
"Failed to get response from: {} after {} attempts",
&webhook_url, attempt
))?;

serde_json::from_str(&response_text).context(format!(
"Failed to parse JSON when querying {}: {}",
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ async fn main() -> Result<(), Error> {
info!("Using thread key {}", thread_key);

GoogleChatMessage::from(message)
.send(&webhook_url, &thread_key)
.send(&webhook_url, &thread_key, 0)
.await?;

for pull_request in pull_requests_to_review {
Expand All @@ -198,7 +198,7 @@ async fn main() -> Result<(), Error> {
pull_request.head.repo.name, pull_request.number
);
GoogleChatMessage::from(make_message(pull_request, show_pr_age))
.send(&webhook_url, &thread_key)
.send(&webhook_url, &thread_key, 0)
.await?;
}
} else {
Expand Down

0 comments on commit 1b3c1e3

Please sign in to comment.