Refactored db directory

This commit is contained in:
Benjamin Sherriff
2023-10-21 12:32:50 -04:00
parent 11facd9bad
commit 379de4bdb5
32 changed files with 124 additions and 67 deletions

View File

@@ -0,0 +1,93 @@
use diesel::{r2d2::ConnectionManager as DieselConnectionManager, PgConnection};
use minio::s3::{client::Client as MinioClient, http::BaseUrl, creds::StaticProvider, args::{MakeBucketArgs, BucketExistsArgs}};
use redis::{Client as RedisClient, aio::Connection as RedisConnection};
use siren::ServiceError;
use crate::diesel_migrations::MigrationHarness;
use lazy_static::lazy_static;
use log::{error, info};
use r2d2;
use std::env;
pub mod guilds;
pub mod messages;
pub mod schema;
type DbPool = r2d2::Pool<DieselConnectionManager<PgConnection>>;
pub type DbConnection = r2d2::PooledConnection<DieselConnectionManager<PgConnection>>;
pub const MIGRATIONS: diesel_migrations::EmbeddedMigrations = embed_migrations!();
lazy_static! {
static ref POOL: DbPool = {
let username = env::var("DATABASE_USER").expect("DATABASE_USERNAME is not set");
let password = env::var("DATABASE_PASSWORD").expect("DATABASE_PASSWORD is not set");
let host = env::var("DATABASE_HOST").unwrap_or("localhost".to_string());
let name = env::var("DATABASE_NAME").expect("DATABASE_NAME is not set");
let port = env::var("DATABASE_PORT").unwrap_or("5432".to_string());
let url = format!("postgres://{}:{}@{}:{}/{}", username, password, host, port, name);
let manager = DieselConnectionManager::<PgConnection>::new(url);
DbPool::builder().test_on_check_out(true).build(manager).expect("Failed to create db pool")
};
static ref REDIS: RedisClient = {
let host = env::var("REDIS_HOST").unwrap_or("localhost".to_string());
let port = env::var("REDIS_PORT").unwrap_or("6379".to_string());
let url = format!("redis://{}:{}", host, port);
RedisClient::open(url).expect("Failed to create redis client")
};
static ref MINIO: MinioClient = {
let url = env::var("MINIO_URL").unwrap_or("localhost".to_string());
let port = env::var("MINIO_PORT").unwrap_or("9000".to_string());
let base_url = format!("http://{}:{}", url, port).parse::<BaseUrl>().unwrap();
let user = env::var("MINIO_ROOT_USER").expect("MINIO_ROOT_USER is not set");
let password = env::var("MINIO_ROOT_PASSWORD").expect("MINIO_ROOT_PASSWORD is not set");
let static_provider = StaticProvider::new(
&user,
&password,
None
);
MinioClient::new(
base_url,
Some(Box::new(static_provider)),
None,
None
).expect("Failed to create minio client")
};
}
pub fn init() {
lazy_static::initialize(&POOL);
lazy_static::initialize(&REDIS);
lazy_static::initialize(&MINIO);
let mut pool: DbConnection = connection().expect("Failed to get db connection");
match pool.run_pending_migrations(MIGRATIONS) {
Ok(_) => info!("Database initialized"),
Err(err) => error!("Failed to initialize database; {}", err)
};
}
pub fn connection() -> Result<DbConnection, ServiceError> {
POOL.get()
.map_err(|e| ServiceError::new(500, format!("Failed getting db connection: {}", e)))
}
pub fn redis_connection() -> Result<redis::Connection, ServiceError> {
let conn = REDIS.get_connection()?;
Ok(conn)
}
pub async fn redis_async_connection() -> Result<RedisConnection, ServiceError> {
let conn = REDIS.get_async_connection().await?;
Ok(conn)
}
pub async fn create_bucket(bucket_name: &str) -> Result<(), ServiceError> {
let exists = MINIO.bucket_exists(&BucketExistsArgs::new(&bucket_name).unwrap()).await?;
if !exists {
MINIO.make_bucket(&MakeBucketArgs::new(&bucket_name).unwrap()).await?;
}
Ok(())
}