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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
//! Managed version of the pool.
//!
//! "Managed" means that it requires a [`Manager`] which is responsible for
//! creating and recycling objects as they are needed.
//!
//! # Example
//!
//! ```rust
//! use async_trait::async_trait;
//! use deadpool::managed;
//!
//! #[derive(Debug)]
//! enum Error { Fail }
//!
//! struct Computer {}
//!
//! impl Computer {
//! async fn get_answer(&self) -> i32 {
//! 42
//! }
//! }
//!
//! struct Manager {}
//!
//! #[async_trait]
//! impl managed::Manager for Manager {
//! type Type = Computer;
//! type Error = Error;
//!
//! async fn create(&self) -> Result<Computer, Error> {
//! Ok(Computer {})
//! }
//! async fn recycle(&self, conn: &mut Computer) -> managed::RecycleResult<Error> {
//! Ok(())
//! }
//! }
//!
//! type Pool = managed::Pool<Manager>;
//!
//! #[tokio::main]
//! async fn main() {
//! let mgr = Manager {};
//! let pool = Pool::builder(mgr).max_size(16).build().unwrap();
//! let mut conn = pool.get().await.unwrap();
//! let answer = conn.get_answer().await;
//! assert_eq!(answer, 42);
//! }
//! ```
//!
//! For a more complete example please see
//! [`deadpool-postgres`](https://crates.io/crates/deadpool-postgres) crate.
mod builder;
mod config;
mod dropguard;
mod errors;
mod hooks;
mod metrics;
pub mod reexports;
#[deprecated(
since = "0.9.1",
note = "This module has been deprecated in favor of the dedicated `deadpool-sync` utility crate."
)]
pub mod sync;
use std::{
collections::VecDeque,
convert::TryFrom,
fmt,
future::Future,
marker::PhantomData,
ops::{Deref, DerefMut},
sync::{
atomic::{AtomicUsize, Ordering},
Arc, Mutex, Weak,
},
time::{Duration, Instant},
};
use async_trait::async_trait;
use deadpool_runtime::Runtime;
use retain_mut::RetainMut;
use tokio::sync::{Semaphore, TryAcquireError};
pub use crate::Status;
use self::dropguard::DropGuard;
pub use self::{
builder::{BuildError, PoolBuilder},
config::{CreatePoolError, PoolConfig, Timeouts},
errors::{PoolError, RecycleError, TimeoutType},
hooks::{Hook, HookError, HookErrorCause, HookFuture, HookResult},
metrics::Metrics,
};
/// Result type of the [`Manager::recycle()`] method.
pub type RecycleResult<E> = Result<(), RecycleError<E>>;
/// Manager responsible for creating new [`Object`]s or recycling existing ones.
#[async_trait]
pub trait Manager: Sync + Send {
/// Type of [`Object`]s that this [`Manager`] creates and recycles.
type Type;
/// Error that this [`Manager`] can return when creating and/or recycling
/// [`Object`]s.
type Error;
/// Creates a new instance of [`Manager::Type`].
async fn create(&self) -> Result<Self::Type, Self::Error>;
/// Tries to recycle an instance of [`Manager::Type`].
///
/// # Errors
///
/// Returns [`Manager::Error`] if the instance couldn't be recycled.
async fn recycle(&self, obj: &mut Self::Type) -> RecycleResult<Self::Error>;
/// Detaches an instance of [`Manager::Type`] from this [`Manager`].
///
/// This method is called when using the [`Object::take()`] method for
/// removing an [`Object`] from a [`Pool`]. If the [`Manager`] doesn't hold
/// any references to the handed out [`Object`]s then the default
/// implementation can be used which does nothing.
fn detach(&self, _obj: &mut Self::Type) {}
}
/// Wrapper around the actual pooled object which implements [`Deref`],
/// [`DerefMut`] and [`Drop`] traits.
///
/// Use this object just as if it was of type `T` and upon leaving a scope the
/// [`Drop::drop()`] will take care of returning it to the pool.
#[must_use]
pub struct Object<M: Manager> {
/// The actual object
inner: Option<ObjectInner<M>>,
/// Pool to return the pooled object to.
pool: Weak<PoolInner<M>>,
}
impl<M> fmt::Debug for Object<M>
where
M: fmt::Debug + Manager,
M::Type: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Object")
.field("inner", &self.inner)
.finish()
}
}
struct UnreadyObject<'a, M: Manager> {
inner: Option<ObjectInner<M>>,
pool: &'a PoolInner<M>,
}
impl<'a, M: Manager> UnreadyObject<'a, M> {
fn ready(mut self) -> ObjectInner<M> {
self.inner.take().unwrap()
}
}
impl<'a, M: Manager> Drop for UnreadyObject<'a, M> {
fn drop(&mut self) {
if let Some(mut inner) = self.inner.take() {
self.pool.slots.lock().unwrap().size -= 1;
self.pool.manager.detach(&mut inner.obj);
}
}
}
impl<'a, M: Manager> Deref for UnreadyObject<'a, M> {
type Target = ObjectInner<M>;
fn deref(&self) -> &Self::Target {
self.inner.as_ref().unwrap()
}
}
impl<'a, M: Manager> DerefMut for UnreadyObject<'a, M> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.inner.as_mut().unwrap()
}
}
#[derive(Debug)]
pub(crate) struct ObjectInner<M: Manager> {
/// Actual pooled object.
obj: M::Type,
/// Object metrics.
metrics: Metrics,
}
impl<M: Manager> Object<M> {
/// Takes this [`Object`] from its [`Pool`] permanently. This reduces the
/// size of the [`Pool`].
#[must_use]
pub fn take(mut this: Self) -> M::Type {
let mut inner = this.inner.take().unwrap().obj;
if let Some(pool) = Object::pool(&this) {
pool.inner.detach_object(&mut inner)
}
inner
}
/// Get object statistics
pub fn metrics(this: &Self) -> &Metrics {
&this.inner.as_ref().unwrap().metrics
}
/// Returns the [`Pool`] this [`Object`] belongs to.
///
/// Since [`Object`]s only hold a [`Weak`] reference to the [`Pool`] they
/// come from, this can fail and return [`None`] instead.
pub fn pool(this: &Self) -> Option<Pool<M>> {
this.pool.upgrade().map(|inner| Pool {
inner,
_wrapper: PhantomData::default(),
})
}
}
impl<M: Manager> Drop for Object<M> {
fn drop(&mut self) {
if let Some(inner) = self.inner.take() {
if let Some(pool) = self.pool.upgrade() {
pool.return_object(inner)
}
}
}
}
impl<M: Manager> Deref for Object<M> {
type Target = M::Type;
fn deref(&self) -> &M::Type {
&self.inner.as_ref().unwrap().obj
}
}
impl<M: Manager> DerefMut for Object<M> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner.as_mut().unwrap().obj
}
}
impl<M: Manager> AsRef<M::Type> for Object<M> {
fn as_ref(&self) -> &M::Type {
self
}
}
impl<M: Manager> AsMut<M::Type> for Object<M> {
fn as_mut(&mut self) -> &mut M::Type {
self
}
}
/// Generic object and connection pool.
///
/// This struct can be cloned and transferred across thread boundaries and uses
/// reference counting for its internal state.
pub struct Pool<M: Manager, W: From<Object<M>> = Object<M>> {
inner: Arc<PoolInner<M>>,
_wrapper: PhantomData<fn() -> W>,
}
// Implemented manually to avoid unnecessary trait bound on `W` type parameter.
impl<M, W> fmt::Debug for Pool<M, W>
where
M: fmt::Debug + Manager,
M::Type: fmt::Debug,
W: From<Object<M>>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pool")
.field("inner", &self.inner)
.field("wrapper", &self._wrapper)
.finish()
}
}
impl<M: Manager, W: From<Object<M>>> Clone for Pool<M, W> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_wrapper: PhantomData::default(),
}
}
}
impl<M: Manager, W: From<Object<M>>> Pool<M, W> {
/// Instantiates a builder for a new [`Pool`].
///
/// This is the only way to create a [`Pool`] instance.
pub fn builder(manager: M) -> PoolBuilder<M, W> {
PoolBuilder::new(manager)
}
pub(crate) fn from_builder(builder: PoolBuilder<M, W>) -> Self {
Self {
inner: Arc::new(PoolInner {
manager: Box::new(builder.manager),
slots: Mutex::new(Slots {
vec: VecDeque::with_capacity(builder.config.max_size),
size: 0,
max_size: builder.config.max_size,
}),
users: AtomicUsize::new(0),
semaphore: Semaphore::new(builder.config.max_size),
config: builder.config,
hooks: builder.hooks,
runtime: builder.runtime,
}),
_wrapper: PhantomData::default(),
}
}
/// Retrieves an [`Object`] from this [`Pool`] or waits for one to
/// become available.
///
/// # Errors
///
/// See [`PoolError`] for details.
pub async fn get(&self) -> Result<W, PoolError<M::Error>> {
self.timeout_get(&self.timeouts()).await
}
/// Retrieves an [`Object`] from this [`Pool`] and doesn't wait if there is
/// currently no [`Object`] available and the maximum [`Pool`] size has
/// been reached.
///
/// # Errors
///
/// See [`PoolError`] for details.
#[deprecated(
since = "0.9.3",
note = "The name of this method is highly misleading. Please use timeout_get instead. e.g.\n`pool.timeout_get(&Timeouts { wait: Some(Duration::ZERO), ..pool.timeouts() })`"
)]
pub async fn try_get(&self) -> Result<W, PoolError<M::Error>> {
self.timeout_get(&Timeouts {
wait: Some(Duration::ZERO),
..self.timeouts()
})
.await
}
/// Retrieves an [`Object`] from this [`Pool`] using a different `timeout`
/// than the configured one.
///
/// # Errors
///
/// See [`PoolError`] for details.
pub async fn timeout_get(&self, timeouts: &Timeouts) -> Result<W, PoolError<M::Error>> {
let _ = self.inner.users.fetch_add(1, Ordering::Relaxed);
let users_guard = DropGuard(|| {
let _ = self.inner.users.fetch_sub(1, Ordering::Relaxed);
});
let non_blocking = match timeouts.wait {
Some(t) => t.as_nanos() == 0,
None => false,
};
let permit = if non_blocking {
self.inner.semaphore.try_acquire().map_err(|e| match e {
TryAcquireError::Closed => PoolError::Closed,
TryAcquireError::NoPermits => PoolError::Timeout(TimeoutType::Wait),
})?
} else {
apply_timeout(
self.inner.runtime,
TimeoutType::Wait,
timeouts.wait,
async {
self.inner
.semaphore
.acquire()
.await
.map_err(|_| PoolError::Closed)
},
)
.await?
};
let inner_obj = loop {
let inner_obj = self.inner.slots.lock().unwrap().vec.pop_front();
if let Some(inner_obj) = inner_obj {
let mut unready_obj = UnreadyObject {
inner: Some(inner_obj),
pool: &self.inner,
};
// Apply pre_recycle hooks
if let Some(_e) = self
.inner
.hooks
.pre_recycle
.apply(&mut unready_obj, PoolError::PreRecycleHook)
.await?
{
continue;
}
if apply_timeout(
self.inner.runtime,
TimeoutType::Recycle,
timeouts.recycle,
self.inner.manager.recycle(&mut unready_obj.obj),
)
.await
.is_err()
{
continue;
}
// Apply post_recycle hooks
if let Some(_e) = self
.inner
.hooks
.post_recycle
.apply(&mut unready_obj, PoolError::PostRecycleHook)
.await?
{
continue;
}
unready_obj.metrics.recycle_count += 1;
unready_obj.metrics.recycled = Some(Instant::now());
break unready_obj.ready();
} else {
// Create new object
let mut unready_obj = UnreadyObject {
inner: Some(ObjectInner {
obj: apply_timeout(
self.inner.runtime,
TimeoutType::Create,
timeouts.create,
self.inner.manager.create(),
)
.await?,
metrics: Metrics::default(),
}),
pool: &self.inner,
};
self.inner.slots.lock().unwrap().size += 1;
// Apply post_create hooks
if let Some(_e) = self
.inner
.hooks
.post_create
.apply(&mut *unready_obj, PoolError::PostCreateHook)
.await?
{
continue;
}
break unready_obj.ready();
}
};
users_guard.disarm();
permit.forget();
Ok(Object {
inner: Some(inner_obj),
pool: Arc::downgrade(&self.inner),
}
.into())
}
/**
* Resize the pool. This change the `max_size` of the pool dropping
* excess objects and/or making space for new ones.
*
* If the pool is closed this method does nothing. The [`Pool::status`] method
* always reports a `max_size` of 0 for closed pools.
*/
pub fn resize(&self, max_size: usize) {
if self.inner.semaphore.is_closed() {
return;
}
let mut slots = self.inner.slots.lock().unwrap();
let old_max_size = slots.max_size;
slots.max_size = max_size;
// shrink pool
if max_size < old_max_size {
while slots.size > slots.max_size {
if let Ok(permit) = self.inner.semaphore.try_acquire() {
permit.forget();
if slots.vec.pop_front().is_some() {
slots.size -= 1;
}
} else {
break;
}
}
// Create a new VecDeque with a smaller capacity
let mut vec = VecDeque::with_capacity(max_size);
for obj in slots.vec.drain(..) {
vec.push_back(obj);
}
slots.vec = vec;
}
// grow pool
if max_size > old_max_size {
let additional = slots.max_size - slots.size;
slots.vec.reserve_exact(additional);
self.inner.semaphore.add_permits(additional);
}
}
/// Retains only the objects specified by the given function.
///
/// This function is typically used to remove objects from
/// the pool based on their current state or metrics.
///
/// **Caution:** This function blocks the entire pool while
/// it is running. Therefore the given function should not
/// block.
///
/// The following example starts a background task that
/// runs every 30 seconds and removes objects from the pool
/// that haven't been used for more than one minute.
///
/// ```rust,ignore
/// let interval = Duration::from_secs(30);
/// let max_age = Duration::from_secs(60);
/// tokio::spawn(async move {
/// loop {
/// tokio::time::sleep(interval).await;
/// pool.retain(|_, metrics| metrics.last_used() < max_age);
/// }
/// });
/// ```
pub fn retain(&self, f: impl Fn(&M::Type, Metrics) -> bool) {
let mut guard = self.inner.slots.lock().unwrap();
let len_before = guard.vec.len();
RetainMut::retain_mut(&mut guard.vec, |obj| {
if f(&obj.obj, obj.metrics) {
true
} else {
self.manager().detach(&mut obj.obj);
false
}
});
guard.size -= len_before - guard.vec.len();
}
/// Get current timeout configuration
pub fn timeouts(&self) -> Timeouts {
self.inner.config.timeouts
}
/// Closes this [`Pool`].
///
/// All current and future tasks waiting for [`Object`]s will return
/// [`PoolError::Closed`] immediately.
///
/// This operation resizes the pool to 0.
pub fn close(&self) {
self.resize(0);
self.inner.semaphore.close();
}
/// Indicates whether this [`Pool`] has been closed.
pub fn is_closed(&self) -> bool {
self.inner.semaphore.is_closed()
}
/// Retrieves [`Status`] of this [`Pool`].
#[must_use]
pub fn status(&self) -> Status {
let slots = self.inner.slots.lock().unwrap();
let used = self.inner.users.load(Ordering::Relaxed);
let available = isize::try_from(slots.size).unwrap() - isize::try_from(used).unwrap();
Status {
max_size: slots.max_size,
size: slots.size,
available,
}
}
/// Returns [`Manager`] of this [`Pool`].
#[must_use]
pub fn manager(&self) -> &M {
&*self.inner.manager
}
}
struct PoolInner<M: Manager> {
manager: Box<M>,
slots: Mutex<Slots<ObjectInner<M>>>,
/// Number of available [`Object`]s in the [`Pool`]. If there are no
/// [`Object`]s in the [`Pool`] this number can become negative and store
/// the number of [`Future`]s waiting for an [`Object`].
users: AtomicUsize,
semaphore: Semaphore,
config: PoolConfig,
runtime: Option<Runtime>,
hooks: hooks::Hooks<M>,
}
#[derive(Debug)]
struct Slots<T> {
vec: VecDeque<T>,
size: usize,
max_size: usize,
}
// Implemented manually to avoid unnecessary trait bound on the struct.
impl<M> fmt::Debug for PoolInner<M>
where
M: fmt::Debug + Manager,
M::Type: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PoolInner")
.field("manager", &self.manager)
.field("slots", &self.slots)
.field("used", &self.users)
.field("semaphore", &self.semaphore)
.field("config", &self.config)
.field("runtime", &self.runtime)
.field("hooks", &self.hooks)
.finish()
}
}
impl<M: Manager> PoolInner<M> {
fn return_object(&self, mut inner: ObjectInner<M>) {
let _ = self.users.fetch_sub(1, Ordering::Relaxed);
let mut slots = self.slots.lock().unwrap();
if slots.size <= slots.max_size {
slots.vec.push_back(inner);
drop(slots);
self.semaphore.add_permits(1);
} else {
slots.size -= 1;
drop(slots);
self.manager.detach(&mut inner.obj);
}
}
fn detach_object(&self, obj: &mut M::Type) {
let _ = self.users.fetch_sub(1, Ordering::Relaxed);
let mut slots = self.slots.lock().unwrap();
let add_permits = slots.size <= slots.max_size;
slots.size -= 1;
drop(slots);
if add_permits {
self.semaphore.add_permits(1);
}
self.manager.detach(obj);
}
}
async fn apply_timeout<O, E>(
runtime: Option<Runtime>,
timeout_type: TimeoutType,
duration: Option<Duration>,
future: impl Future<Output = Result<O, impl Into<PoolError<E>>>>,
) -> Result<O, PoolError<E>> {
match (runtime, duration) {
(_, None) => future.await.map_err(Into::into),
(Some(runtime), Some(duration)) => runtime
.timeout(duration, future)
.await
.ok_or(PoolError::Timeout(timeout_type))?
.map_err(Into::into),
(None, Some(_)) => Err(PoolError::NoRuntimeSpecified),
}
}