Skip to content

Commit

Permalink
chore: use tryhard as retry crate
Browse files Browse the repository at this point in the history
  • Loading branch information
Threated committed Jul 22, 2024
1 parent 7899eb1 commit dff9045
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ rand = { default-features = false, version = "0.8.5" }
futures-util = { version = "0.3", default-features = false, features = ["std"] }
sqlx = { version = "0.7.4", features = [ "runtime-tokio", "postgres", "macros", "chrono"] }
sqlx-pgrow-serde = "0.2.0"
tokio-retry = "0.3"
tryhard = "0.5"

# Logging
tracing = { version = "0.1.37", default_features = false }
Expand Down
17 changes: 6 additions & 11 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::{postgres::PgPoolOptions, postgres::PgRow, PgPool};
use sqlx_pgrow_serde::SerMapPgRow;
use std::collections::HashMap;
use std::{collections::HashMap, time::Duration};
use tracing::{warn, info, debug};
use tokio_retry::strategy::{ExponentialBackoff, jitter};
use tokio_retry::Retry;


#[derive(Serialize, Deserialize, Debug, Default, Clone)]
Expand All @@ -19,11 +17,7 @@ include!(concat!(env!("OUT_DIR"), "/sql_replace_map.rs"));
pub async fn get_pg_connection_pool(pg_url: &str, max_attempts: u32) -> Result<PgPool, FocusError> {
info!("Trying to establish a PostgreSQL connection pool");

let retry_strategy = ExponentialBackoff::from_millis(1000)
.map(jitter)
.take(max_attempts as usize);

let result = Retry::spawn(retry_strategy, || async {
tryhard::retry_fn(|| async {
info!("Attempting to connect to PostgreSQL");
PgPoolOptions::new()
.max_connections(10)
Expand All @@ -33,9 +27,10 @@ pub async fn get_pg_connection_pool(pg_url: &str, max_attempts: u32) -> Result<P
warn!("Failed to connect to PostgreSQL: {}", e);
FocusError::CannotConnectToDatabase(e.to_string())
})
}).await;

result
})
.retries(max_attempts)
.exponential_backoff(Duration::from_secs(2))
.await
}


Expand Down

0 comments on commit dff9045

Please sign in to comment.