Skip to content

Commit

Permalink
feat: retry mongodb connection (ping) on start up to 50 times
Browse files Browse the repository at this point in the history
Signed-off-by: Stefano Cappa <[email protected]>
  • Loading branch information
Ks89 committed Aug 20, 2024
1 parent 487cb50 commit b2e00f2
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 10 deletions.
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ks89-register"
version = "1.0.0"
version = "1.1.0"
edition = "2021"
resolver = "2"

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ GitHub releases [HERE](https://github.com/home-anthill/register/releases)

Versions:

- 20/08/2024 - 1.1.0
- 19/08/2024 - 1.0.2
- 19/05/2024 - 1.0.1
- 19/05/2024 - 1.0.0
Expand Down
28 changes: 24 additions & 4 deletions src/db/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::config::Env;
use std::env;
use std::future::Future;
use log::{error, info, warn};
use mongodb::bson::doc;
use mongodb::options::{ClientOptions, ServerApi, ServerApiVersion};
Expand Down Expand Up @@ -31,7 +32,6 @@ async fn connect(env_config: Env) -> mongodb::error::Result<Database> {
};

let mut client_options = ClientOptions::parse(mongo_uri).await?;

// Set the server_api field of the client_options object to Stable API version 1
let server_api = ServerApi::builder().version(ServerApiVersion::V1).build();
client_options.server_api = Some(server_api);
Expand All @@ -43,9 +43,29 @@ async fn connect(env_config: Env) -> mongodb::error::Result<Database> {
let database = client.database(mongo_db_name.as_str());

info!(target: "app", "Pinging MongoDB server...");
database.run_command(doc! { "ping": 1 }).await?;

info!(target: "app", "MongoDB connected!");
retry_connect_mongodb(|| async { database.run_command(doc! { "ping": 1 }).await }, 50).await?;

Ok(database)
}

async fn retry_connect_mongodb<T, E, Fut, F>(mut f: F, retries: usize) -> Result<T, E>
where
F: FnMut() -> Fut,
Fut: Future<Output=Result<T, E>>,
{
let mut count = 0;
loop {
let result = f().await;
if result.is_ok() {
info!(target: "app", "MongoDB connected!");
return result;
} else {
if count >= retries {
error!(target: "app", "Cannot connect to MongoDB, max tries reached");
return result;
}
count += 1;
warn!(target: "app", "MongoDB ping failed (count={}), retrying...", count);
}
}
}

0 comments on commit b2e00f2

Please sign in to comment.