From 892ff73cc5f80838aa789466c1c0bf4e2ddc694a Mon Sep 17 00:00:00 2001 From: naskya Date: Tue, 9 Jul 2024 16:37:05 +0900 Subject: [PATCH] fix (backend-rs): use tokio::sync::OnceCell for connection pools --- packages/backend-rs/src/database/postgresql.rs | 14 +++++++++----- packages/backend-rs/src/database/redis.rs | 9 ++++++--- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/packages/backend-rs/src/database/postgresql.rs b/packages/backend-rs/src/database/postgresql.rs index fbc7fe7018..33df247ddd 100644 --- a/packages/backend-rs/src/database/postgresql.rs +++ b/packages/backend-rs/src/database/postgresql.rs @@ -1,12 +1,12 @@ //! PostgreSQL interface use crate::config::CONFIG; -use once_cell::sync::OnceCell; use sea_orm::{ConnectOptions, Database, DbConn, DbErr}; use std::time::Duration; +use tokio::sync::OnceCell; use tracing::log::LevelFilter; -static DB_CONN: OnceCell = OnceCell::new(); +static DB_CONN: OnceCell = OnceCell::const_new(); async fn init_conn() -> Result<&'static DbConn, DbErr> { let database_uri = format!( @@ -22,10 +22,14 @@ async fn init_conn() -> Result<&'static DbConn, DbErr> { .sqlx_slow_statements_logging_settings(LevelFilter::Warn, Duration::from_secs(3)) .to_owned(); - tracing::info!("initializing connection"); + let conn = DB_CONN + .get_or_try_init(|| async { + tracing::info!("initializing connection"); + Database::connect(option).await + }) + .await?; - let conn = Database::connect(option).await?; - Ok(DB_CONN.get_or_init(move || conn)) + Ok(conn) } /// Returns an async PostgreSQL connection that can be used with [sea_orm] utilities. diff --git a/packages/backend-rs/src/database/redis.rs b/packages/backend-rs/src/database/redis.rs index 1b989da08b..7b1dde16e8 100644 --- a/packages/backend-rs/src/database/redis.rs +++ b/packages/backend-rs/src/database/redis.rs @@ -72,10 +72,13 @@ async fn init_conn_pool() -> Result<(), RedisError> { tracing::info!("initializing connection manager"); let manager = RedisConnectionManager::new(redis_url)?; - tracing::info!("creating connection pool"); - let pool = Pool::builder().build(manager).await?; + CONN_POOL + .get_or_try_init(|| async { + tracing::info!("creating connection pool"); + Pool::builder().build(manager).await + }) + .await?; - CONN_POOL.get_or_init(|| async { pool }).await; Ok(()) }