diff --git a/Cargo.lock b/Cargo.lock index a053873..27fb948 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1016,7 +1016,7 @@ dependencies = [ [[package]] name = "ks89-register" -version = "1.0.0" +version = "1.1.0" dependencies = [ "dotenvy", "envy", @@ -2474,15 +2474,15 @@ dependencies = [ [[package]] name = "unicode-properties" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4259d9d4425d9f0661581b804cb85fe66a4c631cadd8f490d1c13a35d5d9291" +checksum = "52ea75f83c0137a9b98608359a5f1af8144876eb67bcb1ce837368e906a9f524" [[package]] name = "unicode-xid" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" +checksum = "229730647fbc343e3a80e463c1db7f78f3855d3f3739bee0dda773c9a037c90a" [[package]] name = "universal-hash" diff --git a/Cargo.toml b/Cargo.toml index be1c2d4..0bc83ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ks89-register" -version = "1.0.0" +version = "1.1.0" edition = "2021" resolver = "2" diff --git a/README.md b/README.md index c82adeb..a3b0b13 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/db/mod.rs b/src/db/mod.rs index 621a977..f89dc57 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -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}; @@ -31,7 +32,6 @@ async fn connect(env_config: Env) -> mongodb::error::Result { }; 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); @@ -43,9 +43,29 @@ async fn connect(env_config: Env) -> mongodb::error::Result { 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(mut f: F, retries: usize) -> Result +where + F: FnMut() -> Fut, + Fut: Future>, +{ + 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); + } + } +}