Skip to content

Commit

Permalink
refactor: Conditionally sleep between Chat API requests
Browse files Browse the repository at this point in the history
For a slight performance improvement only sleep between Chat API requests on a 429 response,
as opposed to between every request.
  • Loading branch information
akash1810 committed Nov 5, 2024
1 parent 9d9af0b commit 2a9fceb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
21 changes: 17 additions & 4 deletions src/google.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::time;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use url::Url;
use log::info;

#[derive(Serialize, Deserialize, Debug)]
pub struct GoogleChatMessage {
Expand Down Expand Up @@ -40,14 +42,25 @@ impl GoogleChatMessage {
.body(serde_json::to_string(&self)?)
.header("User-Agent", "GU-PR-Bot")
.send()
.await?
.text()
.await?;

if response.status().eq(&reqwest::StatusCode::TOO_MANY_REQUESTS) {
/*
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());
tokio::time::sleep(time::Duration::from_millis(1500)).await;
Box::pin(self.send(webhook_url, thread_key)).await?;
}

let response_text = response.text()
.await
.context(format!("Failed to get response from: {}", &webhook_url))?;

serde_json::from_str(&response).context(format!(
serde_json::from_str(&response_text).context(format!(
"Failed to parse JSON when querying {}: {}",
&webhook_url, response
&webhook_url, response_text
))
}
}
Expand Down
8 changes: 1 addition & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ mod google;
use anyhow::{Context, Error};
use chrono::{DateTime, Datelike, Utc};
use log::{info, Level};
use std::{env, time};
use std::env;

use github::GithubPullRequest;
use google::GoogleChatMessage;
Expand Down Expand Up @@ -193,12 +193,6 @@ async fn main() -> Result<(), Error> {
.await?;

for pull_request in pull_requests_to_review {
/*
Sleep for 1 second to avoid rate limiting, at 60 requests per minute.
See https://developers.google.com/workspace/chat/limits
*/
tokio::time::sleep(time::Duration::from_secs(1)).await;

info!("Sending message for PR {} #{}", pull_request.head.repo.name, pull_request.number);
GoogleChatMessage::from(make_message(pull_request, show_pr_age))
.send(&webhook_url, &thread_key)
Expand Down

0 comments on commit 2a9fceb

Please sign in to comment.