Skip to content

Commit

Permalink
Replace RecycleError message variants by Cow<'static, str>
Browse files Browse the repository at this point in the history
  • Loading branch information
bikeshedder committed Feb 29, 2024
1 parent 8299972 commit dfc4c9f
Show file tree
Hide file tree
Showing 11 changed files with 37 additions and 37 deletions.
4 changes: 2 additions & 2 deletions diesel/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,14 +148,14 @@ where

async fn recycle(&self, obj: &mut Self::Type, _: &Metrics) -> RecycleResult<Self::Error> {
if obj.is_mutex_poisoned() {
return Err(RecycleError::StaticMessage(
return Err(RecycleError::message(
"Mutex is poisoned. Connection is considered unusable.",
));
}
let config = Arc::clone(&self.manager_config);
obj.interact(move |conn| config.recycling_method.perform_recycle_check(conn))
.await
.map_err(|e| RecycleError::Message(format!("Panic: {:?}", e)))
.map_err(|e| RecycleError::message(format!("Panic: {:?}", e)))
.and_then(|r| r.map_err(RecycleError::Backend))
}
}
Expand Down
2 changes: 1 addition & 1 deletion lapin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl managed::Manager for Manager {
async fn recycle(&self, conn: &mut lapin::Connection, _: &Metrics) -> RecycleResult {
match conn.status().state() {
lapin::ConnectionState::Connected => Ok(()),
other_state => Err(RecycleError::Message(format!(
other_state => Err(RecycleError::message(format!(
"lapin connection is in state: {:?}",
other_state
))),
Expand Down
2 changes: 1 addition & 1 deletion postgres/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ impl managed::Manager for Manager {
async fn recycle(&self, client: &mut ClientWrapper, _: &Metrics) -> RecycleResult {
if client.is_closed() {
tracing::warn!(target: "deadpool.postgres", "Connection could not be recycled: Connection closed");
return Err(RecycleError::StaticMessage("Connection closed"));
return Err(RecycleError::message("Connection closed"));
}
match self.config.recycling_method.query() {
Some(sql) => match client.simple_query(sql).await {
Expand Down
6 changes: 3 additions & 3 deletions r2d2/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,19 +54,19 @@ where

async fn recycle(&self, obj: &mut Self::Type, _: &Metrics) -> RecycleResult<Self::Error> {
if obj.is_mutex_poisoned() {
return Err(RecycleError::StaticMessage(
return Err(RecycleError::message(
"Mutex is poisoned. Connection is considered unusable.",
));
}
let r2d2_manager = self.r2d2_manager.clone();
obj.interact::<_, RecycleResult<Self::Error>>(move |obj| {
if r2d2_manager.has_broken(obj) {
Err(RecycleError::StaticMessage("Connection is broken"))
Err(RecycleError::message("Connection is broken"))
} else {
r2d2_manager.is_valid(obj).map_err(RecycleError::Backend)
}
})
.await
.map_err(|e| RecycleError::Message(format!("Interaction failed: {}", e)))?
.map_err(|e| RecycleError::message(format!("Interaction failed: {}", e)))?
}
}
4 changes: 1 addition & 3 deletions redis/src/cluster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,7 @@ impl managed::Manager for Manager {
if n == ping_number {
Ok(())
} else {
Err(managed::RecycleError::StaticMessage(
"Invalid PING response",
))
Err(managed::RecycleError::message("Invalid PING response"))
}
}
}
4 changes: 1 addition & 3 deletions redis/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,7 @@ impl managed::Manager for Manager {
if n == ping_number {
Ok(())
} else {
Err(managed::RecycleError::StaticMessage(
"Invalid PING response",
))
Err(managed::RecycleError::message("Invalid PING response"))
}
}
}
4 changes: 2 additions & 2 deletions sqlite/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,11 @@ impl managed::Manager for Manager {
let n: usize = conn
.interact(move |conn| conn.query_row("SELECT $1", [recycle_count], |row| row.get(0)))
.await
.map_err(|e| RecycleError::Message(format!("{}", e)))??;
.map_err(|e| RecycleError::message(format!("{}", e)))??;
if n == recycle_count {
Ok(())
} else {
Err(RecycleError::StaticMessage("Recycle count mismatch"))
Err(RecycleError::message("Recycle count mismatch"))
}
}
}
19 changes: 10 additions & 9 deletions src/managed/errors.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt;
use std::{borrow::Cow, fmt};

use super::hooks::HookError;

Expand All @@ -8,15 +8,20 @@ use super::hooks::HookError;
#[derive(Debug)]
pub enum RecycleError<E> {
/// Recycling failed for some other reason.
Message(String),

/// Recycling failed for some other reason.
StaticMessage(&'static str),
Message(Cow<'static, str>),

/// Error caused by the backend.
Backend(E),
}

impl<E> RecycleError<E> {
/// Convenience constructor function for the `HookError::Message`
/// variant.
pub fn message(msg: impl Into<Cow<'static, str>>) -> Self {
Self::Message(msg.into())
}
}

impl<E> From<E> for RecycleError<E> {
fn from(e: E) -> Self {
Self::Backend(e)
Expand All @@ -27,9 +32,6 @@ impl<E: fmt::Display> fmt::Display for RecycleError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Message(msg) => write!(f, "Error occurred while recycling an object: {}", msg),
Self::StaticMessage(msg) => {
write!(f, "Error occurred while recycling an object: {}", msg)
}
Self::Backend(e) => write!(f, "Error occurred while recycling an object: {}", e),
}
}
Expand All @@ -39,7 +41,6 @@ impl<E: std::error::Error + 'static> std::error::Error for RecycleError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Message(_) => None,
Self::StaticMessage(_) => None,
Self::Backend(e) => Some(e),
}
}
Expand Down
17 changes: 10 additions & 7 deletions src/managed/hooks.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Hooks allowing to run code when creating and/or recycling objects.

use std::{fmt, future::Future, pin::Pin};
use std::{borrow::Cow, fmt, future::Future, pin::Pin};

use super::{Manager, Metrics, ObjectInner};

Expand Down Expand Up @@ -65,20 +65,24 @@ impl<M: Manager> fmt::Debug for Hook<M> {
#[derive(Debug)]
pub enum HookError<E> {
/// Hook failed for some other reason.
Message(String),

/// Hook failed for some other reason.
StaticMessage(&'static str),
Message(Cow<'static, str>),

/// Error caused by the backend.
Backend(E),
}

impl<E> HookError<E> {
/// Convenience constructor function for the `HookError::Message`
/// variant.
pub fn message(msg: impl Into<Cow<'static, str>>) -> Self {
Self::Message(msg.into())
}
}

impl<E: fmt::Display> fmt::Display for HookError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Message(msg) => write!(f, "{}", msg),
Self::StaticMessage(msg) => write!(f, "{}", msg),
Self::Backend(e) => write!(f, "{}", e),
}
}
Expand All @@ -88,7 +92,6 @@ impl<E: std::error::Error + 'static> std::error::Error for HookError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Message(_) => None,
Self::StaticMessage(_) => None,
Self::Backend(e) => Some(e),
}
}
Expand Down
6 changes: 3 additions & 3 deletions tests/managed_cancellation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ fn pools(max_size: usize) -> impl Iterator<Item = Pool<GatedManager>> {
.post_create
.open()
.await
.map_err(|_| HookError::StaticMessage("Fail"))?;
.map_err(|_| HookError::message("Fail"))?;
Ok(())
})
}))
Expand All @@ -72,7 +72,7 @@ fn pools(max_size: usize) -> impl Iterator<Item = Pool<GatedManager>> {
.pre_recycle
.open()
.await
.map_err(|_| HookError::StaticMessage("pre_recycle gate set to error"))?;
.map_err(|_| HookError::message("pre_recycle gate set to error"))?;
Ok(())
})
}))
Expand All @@ -82,7 +82,7 @@ fn pools(max_size: usize) -> impl Iterator<Item = Pool<GatedManager>> {
.post_recycle
.open()
.await
.map_err(|_| HookError::StaticMessage("post_recycle gate set to error"))?;
.map_err(|_| HookError::message("post_recycle gate set to error"))?;
Ok(())
})
}))
Expand Down
6 changes: 3 additions & 3 deletions tests/managed_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ async fn post_create_err_abort() {
.post_create(Hook::sync_fn(|obj, _| {
(*obj % 2 == 0)
.then_some(())
.ok_or(HookError::StaticMessage("odd creation"))
.ok_or(HookError::message("odd creation"))
}))
.build()
.unwrap();
Expand Down Expand Up @@ -105,7 +105,7 @@ async fn pre_recycle_err_continue() {
.max_size(1)
.pre_recycle(Hook::sync_fn(|_, metrics| {
if metrics.recycle_count > 0 {
Err(HookError::StaticMessage("Fail!"))
Err(HookError::message("Fail!"))
} else {
Ok(())
}
Expand Down Expand Up @@ -156,7 +156,7 @@ async fn post_recycle_err_continue() {
.max_size(1)
.post_recycle(Hook::sync_fn(|_, metrics| {
if metrics.recycle_count > 0 {
Err(HookError::StaticMessage("Fail!"))
Err(HookError::message("Fail!"))
} else {
Ok(())
}
Expand Down

0 comments on commit dfc4c9f

Please sign in to comment.