From 5723f127c1dee92e58028505ac41ae4410c3fd72 Mon Sep 17 00:00:00 2001 From: Nya <7364785+liquidnya@users.noreply.github.com> Date: Wed, 26 Oct 2022 11:32:45 +0200 Subject: [PATCH] Fix panic when dropping sync 'ConnectionPool'. Fixes #2375. --- contrib/sync_db_pools/lib/src/connection.rs | 6 +++- contrib/sync_db_pools/lib/tests/shutdown.rs | 32 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 contrib/sync_db_pools/lib/tests/shutdown.rs diff --git a/contrib/sync_db_pools/lib/src/connection.rs b/contrib/sync_db_pools/lib/src/connection.rs index e3a0fd0a..355a55d1 100644 --- a/contrib/sync_db_pools/lib/src/connection.rs +++ b/contrib/sync_db_pools/lib/src/connection.rs @@ -195,7 +195,11 @@ impl Drop for Connection { impl Drop for ConnectionPool { fn drop(&mut self) { let pool = self.pool.take(); - tokio::task::spawn_blocking(move || drop(pool)); + // Only use spawn_blocking if the Tokio runtime is still available + if let Ok(handle) = tokio::runtime::Handle::try_current() { + handle.spawn_blocking(move || drop(pool)); + } + // Otherwise the pool will be dropped on the current thread } } diff --git a/contrib/sync_db_pools/lib/tests/shutdown.rs b/contrib/sync_db_pools/lib/tests/shutdown.rs new file mode 100644 index 00000000..8f76b0fa --- /dev/null +++ b/contrib/sync_db_pools/lib/tests/shutdown.rs @@ -0,0 +1,32 @@ +#[cfg(all(feature = "diesel_sqlite_pool"))] +#[cfg(test)] +mod sqlite_shutdown_test { + use rocket::{async_test, Build, Rocket}; + use rocket_sync_db_pools::database; + + #[database("test")] + struct Pool(diesel::SqliteConnection); + + async fn rocket() -> Rocket { + use rocket::figment::{util::map, Figment}; + + let options = map!["url" => ":memory:"]; + let config = Figment::from(rocket::Config::debug_default()) + .merge(("databases", map!["test" => &options])); + + rocket::custom(config).attach(Pool::fairing()) + } + + #[test] + fn test_shutdown() { + let _rocket = async_test( + async { + let rocket = rocket().await.ignite().await.expect("unable to ignite"); + // request shutdown + rocket.shutdown().notify(); + rocket.launch().await.expect("unable to launch") + } + ); + // _rocket is dropped here after the runtime is dropped + } +}