[no ci] Update controllers folder

This commit is contained in:
toast 2024-08-03 12:02:54 +10:00
parent 048ce583e8
commit ec1aa9db0a
2 changed files with 31 additions and 28 deletions

View File

@ -9,8 +9,8 @@ use bb8_redis::{
RedisConnectionManager
};
use tokio::time::{
sleep,
Duration
Duration,
sleep
};
#[derive(Debug)]

View File

@ -1,22 +1,24 @@
use crate::internals::utils::token_path;
use std::sync::LazyLock;
use bb8::{Pool, PooledConnection};
use bb8_postgres::PostgresConnectionManager;
use tokio::time::{
Duration,
sleep
};
use tokio_postgres::{
Client,
NoTls,
Error,
config::Config
};
use tokio::time::{
sleep,
Duration
};
use std::{
ops::Deref,
str::FromStr,
sync::Mutex
sync::{
Mutex,
LazyLock
}
};
pub static DATABASE: LazyLock<Mutex<Option<DatabaseController>>> = LazyLock::new(|| Mutex::new(None));
@ -28,27 +30,29 @@ pub struct DatabaseController {
impl DatabaseController {
pub async fn new() -> Result<(), Error> {
let manager = PostgresConnectionManager::new(Config::from_str(token_path().await.postgres_uri.as_str())?, NoTls);
let pool = Pool::builder().build(manager).await?;
let pool = bb8::Pool::builder().build(manager).await?;
let err_name = "Postgres[Error]";
let pool_clone = pool.clone();
tokio::spawn(async move {
let conn = match Self::attempt_connect(&pool_clone).await {
Ok(conn) => {
println!("Postgres[Info]: Successfully connected");
conn
},
Err(y) => {
eprintln!("{}: {}", err_name, y);
return;
}
};
let client: &Client = conn.deref();
loop {
match Self::attempt_connect(&pool_clone).await {
Ok(conn) => {
println!("Postgres[Info]: Successfully connected");
let client: &Client = conn.deref();
/* if let Err(e) = client.batch_execute("").await {
eprintln!("{}: {}", err_name, e);
} */ // Uncomment this if bot is going to use a database
}).await.unwrap();
/* if let Err(e) = client.batch_execute("").await {
eprintln!("{}: {}", err_name, e);
} */ // Uncomment this if bot is going to use a database
},
Err(e) => {
eprintln!("{}: {}", err_name, e);
sleep(Duration::from_secs(5)).await;
}
}
break;
}
});
let controller = Self { pool };
*DATABASE.lock().unwrap() = Some(controller);
@ -56,14 +60,13 @@ impl DatabaseController {
Ok(())
}
async fn attempt_connect<'a>(pool: &'a Pool<PostgresConnectionManager<NoTls>>) -> Result<PooledConnection<'a, PostgresConnectionManager<NoTls>>, bb8::RunError<Error>> {
async fn attempt_connect<'a>(pool: &'a bb8::Pool<PostgresConnectionManager<NoTls>>) -> Result<PooledConnection<'a, PostgresConnectionManager<NoTls>>, bb8::RunError<Error>> {
let mut backoff = 1;
loop {
match pool.get().await {
Ok(conn) => return Ok(conn),
Err(y) => {
eprintln!("Postgres[ConnError]: {}, retrying in {} seconds", y, backoff);
Err(e) => {
eprintln!("Postgres[ConnError]: {}, retrying in {} seconds", e, backoff);
sleep(Duration::from_secs(backoff)).await;
if backoff < 64 {
backoff *= 2;