1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
//! Helpers for writing pools for objects that don't support async and need to
//! be run inside a thread.
pub mod reexports {
//! This module contains all things that should be reexported
//! by backend implementations in order to avoid direct
//! dependencies on the `deadpool` crate itself.
//!
//! This module is the variant that should be used by *sync*
//! backends.
//!
//! Crates based on `deadpool::managed::sync` should include this line:
//! ```rust,ignore
//! pub use deadpool::managed::sync::reexports::*;
//! deadpool::managed_reexports!(
//! "name_of_crate",
//! Manager,
//! Object<Manager>,
//! Error,
//! ConfigError
//! );
//! ```
pub use super::super::reexports::*;
pub use super::{InteractError, SyncGuard};
}
use std::{
any::Any,
fmt,
marker::PhantomData,
ops::{Deref, DerefMut},
sync::{Arc, Mutex, MutexGuard, PoisonError, TryLockError},
};
use crate::{Runtime, SpawnBlockingError};
/// Possible errors returned when [`SyncWrapper::interact()`] fails.
#[derive(Debug)]
pub enum InteractError<E> {
/// Provided callback has panicked.
Panic(Box<dyn Any + Send + 'static>),
/// Callback was aborted.
Aborted,
/// Backend returned an error.
Backend(E),
}
impl<E: fmt::Display> fmt::Display for InteractError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Panic(_) => write!(f, "Panic"),
Self::Aborted => write!(f, "Aborted"),
Self::Backend(e) => write!(f, "Backend error: {}", e),
}
}
}
impl<E: std::error::Error + 'static> std::error::Error for InteractError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Panic(_) | Self::Aborted => None,
Self::Backend(e) => Some(e),
}
}
}
/// Wrapper for objects which only provides blocking functions that need to be
/// called on a separate thread.
///
/// Access to the wrapped object is provided via the [`SyncWrapper::interact()`]
/// method.
#[must_use]
pub struct SyncWrapper<T, E>
where
T: Send + 'static,
E: Send + 'static,
{
obj: Arc<Mutex<Option<T>>>,
runtime: Runtime,
_error: PhantomData<fn() -> E>,
}
// Implemented manually to avoid unnecessary trait bound on `E` type parameter.
impl<T, E> fmt::Debug for SyncWrapper<T, E>
where
T: fmt::Debug + Send + 'static,
E: Send + 'static,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SyncWrapper")
.field("obj", &self.obj)
.field("runtime", &self.runtime)
.field("_error", &self._error)
.finish()
}
}
impl<T, E> SyncWrapper<T, E>
where
T: Send + 'static,
E: Send + 'static,
{
/// Creates a new wrapped object.
pub async fn new<F>(runtime: Runtime, f: F) -> Result<Self, E>
where
F: FnOnce() -> Result<T, E> + Send + 'static,
{
let result = match runtime.spawn_blocking(f).await {
// FIXME: Panicking when the creation panics is not nice.
// In order to handle this properly the Manager::create
// methods needs to support a custom error enum which
// supports a Panic variant.
Err(SpawnBlockingError::Panic(e)) => panic!("{:?}", e),
Ok(obj) => obj,
};
result.map(|obj| Self {
obj: Arc::new(Mutex::new(Some(obj))),
runtime,
_error: PhantomData::default(),
})
}
/// Interacts with the underlying object.
///
/// Expects a closure that takes the object as its parameter.
/// The closure is executed in a separate thread so that the async runtime
/// is not blocked.
pub async fn interact<F, R>(&self, f: F) -> Result<R, InteractError<E>>
where
F: FnOnce(&mut T) -> Result<R, E> + Send + 'static,
R: Send + 'static,
{
let arc = self.obj.clone();
self.runtime
.spawn_blocking(move || {
let mut guard = arc.lock().unwrap();
let conn = guard.as_mut().unwrap();
f(conn)
})
.await
.map_err(|e| match e {
SpawnBlockingError::Panic(p) => InteractError::Panic(p),
})?
.map_err(InteractError::Backend)
}
/// Indicates whether the underlying [`Mutex`] has been poisoned.
///
/// This happens when a panic occurs while interacting with the object.
pub fn is_mutex_poisoned(&self) -> bool {
self.obj.is_poisoned()
}
/// Lock the underlying mutex and return a guard for the inner
/// object.
pub fn lock(&self) -> Result<SyncGuard<'_, T>, PoisonError<MutexGuard<'_, Option<T>>>> {
self.obj.lock().map(SyncGuard)
}
/// Try to lock the underlying mutex and return a guard for the
/// inner object.
pub fn try_lock(&self) -> Result<SyncGuard<'_, T>, TryLockError<MutexGuard<'_, Option<T>>>> {
self.obj.try_lock().map(SyncGuard)
}
}
impl<T, E> Drop for SyncWrapper<T, E>
where
T: Send + 'static,
E: Send + 'static,
{
fn drop(&mut self) {
let arc = self.obj.clone();
// Drop the `rusqlite::Connection` inside a `spawn_blocking`
// as the `drop` function of it can block.
self.runtime
.spawn_blocking_background(move || match arc.lock() {
Ok(mut guard) => drop(guard.take()),
Err(e) => drop(e.into_inner().take()),
})
.unwrap();
}
}
/// This guard is returned when calling `SyncWrapper::lock` or
/// `SyncWrapper::try_lock`. This is basicly just a wrapper around
/// a `MutexGuard` but hides some implementation details.
///
/// **Important:** Any blocking operation using this object
/// should be executed on a separate thread (e.g. via `spawn_blocking`).
#[derive(Debug)]
pub struct SyncGuard<'a, T: Send>(MutexGuard<'a, Option<T>>);
impl<'a, T: Send> Deref for SyncGuard<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.as_ref().unwrap()
}
}
impl<'a, T: Send> DerefMut for SyncGuard<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.as_mut().unwrap()
}
}
impl<'a, T: Send> AsRef<T> for SyncGuard<'a, T> {
fn as_ref(&self) -> &T {
self.0.as_ref().unwrap()
}
}
impl<'a, T: Send> AsMut<T> for SyncGuard<'a, T> {
fn as_mut(&mut self) -> &mut T {
self.0.as_mut().unwrap()
}
}