Skip to content

Commit

Permalink
Cache pool
Browse files Browse the repository at this point in the history
  • Loading branch information
MTRNord committed Sep 8, 2023
1 parent 8697ceb commit 04492f3
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
1 change: 1 addition & 0 deletions crates/erooster_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ tracing-error = "0.2.0"
tracing-subscriber = { version = "0.3.16", features = ["env-filter"] }
url = "2.4.1"
secrecy = "0.8.0"
once_cell = "1.18.0"

[build-dependencies]
vergen = { version = "8.2.4", features = ["git", "gitoxide"] }
Expand Down
25 changes: 20 additions & 5 deletions crates/erooster_core/src/backend/database/postgres.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use crate::{backend::database::Database, config::Config};
use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use color_eyre::Result;
use once_cell::sync::OnceCell;
use rand_core::OsRng;
use secrecy::{ExposeSecret, SecretString};
use sqlx::PgPool;
use sqlx::{pool::PoolOptions, PgPool};
use std::sync::Arc;
use tracing::{debug, debug_span, error, instrument};

Expand All @@ -18,11 +19,25 @@ pub struct Postgres {
impl Database<sqlx::Postgres> for Postgres {
#[instrument(skip(config))]
async fn new(config: Arc<Config>) -> Result<Self> {
let pool = PgPool::connect_lazy(&config.database.postgres_url)
.expect("Failed to connect to postgres");
static INSTANCE: OnceCell<Postgres> = OnceCell::new();

sqlx::migrate!().run(&pool).await?;
Ok(Self { pool })
let pool = INSTANCE.get();

if let Some(pool) = pool {
Ok(pool.clone())
} else {
let pool = PoolOptions::new()
.min_connections(2)
.max_connections(10)
.connect(&config.database.postgres_url)
.await?;
sqlx::migrate!().run(&pool).await?;
let new_self = Self { pool };
INSTANCE
.set(new_self.clone())
.expect("Failed to set INSTANCE");
Ok(new_self)
}
}

#[instrument(skip(self))]
Expand Down
1 change: 1 addition & 0 deletions crates/erooster_core/src/backend/storage/maildir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,7 @@ impl MailStorage<MaildirMailEntry> for MaildirStorage {

#[derive(sqlx::FromRow, Debug)]
struct DbMails {
#[allow(dead_code)]
id: i32,
maildir_id: String,
modseq: i64,
Expand Down

0 comments on commit 04492f3

Please sign in to comment.