Debian Codegraph @

src/pool/inner.rs

raw symbols SCIP
1 use super::connection::{Floating, Idle, Live};
2 use crate::connection::ConnectOptions;
3 use crate::connection::Connection;
4 use crate::database::Database;
5 use crate::error::Error;
6 use crate::pool::{deadline_as_timeout, CloseEvent, Pool, PoolOptions};
7 use crossbeam_queue::ArrayQueue;
8
9 use crate::sync::{AsyncSemaphore, AsyncSemaphoreReleaser};
10
11 use std::cmp;
12 use std::future::Future;
13 use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
14 use std::sync::{Arc, RwLock};
15 use std::task::Poll;
16
17 use crate::logger::private_level_filter_to_trace_level;
18 use crate::pool::options::PoolConnectionMetadata;
19 use crate::private_tracing_dynamic_event;
20 use futures_util::future::{self};
21 use futures_util::FutureExt;
22 use std::time::{Duration, Instant};
23 use tracing::Level;
24
25 pub(crate) struct PoolInner<DB: Database> {
26 pub(super) connect_options: RwLock<Arc<<DB::Connection as Connection>::Options>>,
27 pub(super) idle_conns: ArrayQueue<Idle<DB>>,
28 pub(super) semaphore: AsyncSemaphore,
29 pub(super) size: AtomicU32,
30 pub(super) num_idle: AtomicUsize,
31 is_closed: AtomicBool,
32 pub(super) on_closed: event_listener::Event,
33 pub(super) options: PoolOptions<DB>,
34 pub(crate) acquire_time_level: Option<Level>,
35 pub(crate) acquire_slow_level: Option<Level>,
36 }
37
38 impl<DB: Database> PoolInner<DB> {
39 pub(super) fn new_arc(
40 options: PoolOptions<DB>,
41 connect_options: <DB::Connection as Connection>::Options,
42 ) -> Arc<Self> {
43 let capacity = options.max_connections as usize;
44
45 let semaphore_capacity = if let Some(parent) = &options.parent_pool {
46 assert!(options.max_connections <= parent.options().max_connections);
47 assert_eq!(options.fair, parent.options().fair);
48 // The child pool must steal permits from the parent
49 0
50 } else {
51 capacity
52 };
53
54 let pool = Self {
55 connect_options: RwLock::new(Arc::new(connect_options)),
56 idle_conns: ArrayQueue::new(capacity),
57 semaphore: AsyncSemaphore::new(options.fair, semaphore_capacity),
58 size: AtomicU32::new(0),
59 num_idle: AtomicUsize::new(0),
60 is_closed: AtomicBool::new(false),
61 on_closed: event_listener::Event::new(),
62 acquire_time_level: private_level_filter_to_trace_level(options.acquire_time_level),
63 acquire_slow_level: private_level_filter_to_trace_level(options.acquire_slow_level),
64 options,
65 };
66
67 let pool = Arc::new(pool);
68
69 spawn_maintenance_tasks(&pool);
70
71 pool
72 }
73
74 pub(super) fn size(&self) -> u32 {
75 self.size.load(Ordering::Acquire)
76 }
77
78 pub(super) fn num_idle(&self) -> usize {
79 // We don't use `self.idle_conns.len()` as it waits for the internal
80 // head and tail pointers to stop changing for a moment before calculating the length,
81 // which may take a long time at high levels of churn.
82 //
83 // By maintaining our own atomic count, we avoid that issue entirely.
84 self.num_idle.load(Ordering::Acquire)
85 }
86
87 pub(super) fn is_closed(&self) -> bool {
88 self.is_closed.load(Ordering::Acquire)
89 }
90
91 fn mark_closed(&self) {
92 self.is_closed.store(true, Ordering::Release);
93 self.on_closed.notify(usize::MAX);
94 }
95
96 pub(super) fn close<'a>(self: &'a Arc<Self>) -> impl Future<Output = ()> + 'a {
97 self.mark_closed();
98
99 async move {
100 for permits in 1..=self.options.max_connections {
101 // Close any currently idle connections in the pool.
102 while let Some(idle) = self.idle_conns.pop() {
103 let _ = idle.live.float((*self).clone()).close().await;
104 }
105
106 if self.size() == 0 {
107 break;
108 }
109
110 // Wait for all permits to be released.
111 let _permits = self.semaphore.acquire(permits).await;
112 }
113 }
114 }
115
116 pub(crate) fn close_event(&self) -> CloseEvent {
117 CloseEvent {
118 listener: (!self.is_closed()).then(|| self.on_closed.listen()),
119 }
120 }
121
122 /// Attempt to pull a permit from `self.semaphore` or steal one from the parent.
123 ///
124 /// If we steal a permit from the parent but *don't* open a connection,
125 /// it should be returned to the parent.
126 async fn acquire_permit<'a>(self: &'a Arc<Self>) -> Result<AsyncSemaphoreReleaser<'a>, Error> {
127 let parent = self
128 .parent()
129 // If we're already at the max size, we shouldn't try to steal from the parent.
130 // This is just going to cause unnecessary churn in `acquire()`.
131 .filter(|_| self.size() < self.options.max_connections);
132
133 let acquire_self = self.semaphore.acquire(1).fuse();
134 let mut close_event = self.close_event();
135
136 if let Some(parent) = parent {
137 let acquire_parent = parent.0.semaphore.acquire(1);
138 let parent_close_event = parent.0.close_event();
139
140 futures_util::pin_mut!(
141 acquire_parent,
142 acquire_self,
143 close_event,
144 parent_close_event
145 );
146
147 let mut poll_parent = false;
148
149 future::poll_fn(|cx| {
150 if close_event.as_mut().poll(cx).is_ready() {
151 return Poll::Ready(Err(Error::PoolClosed));
152 }
153
154 if parent_close_event.as_mut().poll(cx).is_ready() {
155 // Propagate the parent's close event to the child.
156 self.mark_closed();
157 return Poll::Ready(Err(Error::PoolClosed));
158 }
159
160 if let Poll::Ready(permit) = acquire_self.as_mut().poll(cx) {
161 return Poll::Ready(Ok(permit));
162 }
163
164 // Don't try the parent right away.
165 if poll_parent {
166 acquire_parent.as_mut().poll(cx).map(Ok)
167 } else {
168 poll_parent = true;
169 cx.waker().wake_by_ref();
170 Poll::Pending
171 }
172 })
173 .await
174 } else {
175 close_event.do_until(acquire_self).await
176 }
177 }
178
179 fn parent(&self) -> Option<&Pool<DB>> {
180 self.options.parent_pool.as_ref()
181 }
182
183 #[inline]
184 pub(super) fn try_acquire(self: &Arc<Self>) -> Option<Floating<DB, Idle<DB>>> {
185 if self.is_closed() {
186 return None;
187 }
188
189 let permit = self.semaphore.try_acquire(1)?;
190
191 self.pop_idle(permit).ok()
192 }
193
194 fn pop_idle<'a>(
195 self: &'a Arc<Self>,
196 permit: AsyncSemaphoreReleaser<'a>,
197 ) -> Result<Floating<DB, Idle<DB>>, AsyncSemaphoreReleaser<'a>> {
198 if let Some(idle) = self.idle_conns.pop() {
199 self.num_idle.fetch_sub(1, Ordering::AcqRel);
200 Ok(Floating::from_idle(idle, (*self).clone(), permit))
201 } else {
202 Err(permit)
203 }
204 }
205
206 pub(super) fn release(&self, floating: Floating<DB, Live<DB>>) {
207 // `options.after_release` and other checks are in `PoolConnection::return_to_pool()`.
208
209 let Floating { inner: idle, guard } = floating.into_idle();
210
211 if self.idle_conns.push(idle).is_err() {
212 panic!("BUG: connection queue overflow in release()");
213 }
214
215 // NOTE: we need to make sure we drop the permit *after* we push to the idle queue
216 // don't decrease the size
217 guard.release_permit();
218
219 self.num_idle.fetch_add(1, Ordering::AcqRel);
220 }
221
222 /// Try to atomically increment the pool size for a new connection.
223 ///
224 /// Returns `Err` if the pool is at max capacity already or is closed.
225 pub(super) fn try_increment_size<'a>(
226 self: &'a Arc<Self>,
227 permit: AsyncSemaphoreReleaser<'a>,
228 ) -> Result<DecrementSizeGuard<DB>, AsyncSemaphoreReleaser<'a>> {
229 let result = self
230 .size
231 .fetch_update(Ordering::AcqRel, Ordering::Acquire, |size| {
232 if self.is_closed() {
233 return None;
234 }
235
236 size.checked_add(1)
237 .filter(|size| size <= &self.options.max_connections)
238 });
239
240 match result {
241 // we successfully incremented the size
242 Ok(_) => Ok(DecrementSizeGuard::from_permit((*self).clone(), permit)),
243 // the pool is at max capacity or is closed
244 Err(_) => Err(permit),
245 }
246 }
247
248 pub(super) async fn acquire(self: &Arc<Self>) -> Result<Floating<DB, Live<DB>>, Error> {
249 if self.is_closed() {
250 return Err(Error::PoolClosed);
251 }
252
253 let acquire_started_at = Instant::now();
254 let deadline = acquire_started_at + self.options.acquire_timeout;
255
256 let acquired = crate::rt::timeout(
257 self.options.acquire_timeout,
258 async {
259 loop {
260 // Handles the close-event internally
261 let permit = self.acquire_permit().await?;
262
263
264 // First attempt to pop a connection from the idle queue.
265 let guard = match self.pop_idle(permit) {
266
267 // Then, check that we can use it...
268 Ok(conn) => match check_idle_conn(conn, &self.options).await {
269
270 // All good!
271 Ok(live) => return Ok(live),
272
273 // if the connection isn't usable for one reason or another,
274 // we get the `DecrementSizeGuard` back to open a new one
275 Err(guard) => guard,
276 },
277 Err(permit) => if let Ok(guard) = self.try_increment_size(permit) {
278 // we can open a new connection
279 guard
280 } else {
281 // This can happen for a child pool that's at its connection limit,
282 // or if the pool was closed between `acquire_permit()` and
283 // `try_increment_size()`.
284 tracing::debug!("woke but was unable to acquire idle connection or open new one; retrying");
285 // If so, we're likely in the current-thread runtime if it's Tokio,
286 // and so we should yield to let any spawned return_to_pool() tasks
287 // execute.
288 crate::rt::yield_now().await;
289 continue;
290 }
291 };
292
293 // Attempt to connect...
294 return self.connect(deadline, guard).await;
295 }
296 }
297 )
298 .await
299 .map_err(|_| Error::PoolTimedOut)??;
300
301 let acquired_after = acquire_started_at.elapsed();
302
303 let acquire_slow_level = self
304 .acquire_slow_level
305 .filter(|_| acquired_after > self.options.acquire_slow_threshold);
306
307 if let Some(level) = acquire_slow_level {
308 private_tracing_dynamic_event!(
309 target: "sqlx::pool::acquire",
310 level,
311 aquired_after_secs = acquired_after.as_secs_f64(),
312 slow_acquire_threshold_secs = self.options.acquire_slow_threshold.as_secs_f64(),
313 "acquired connection, but time to acquire exceeded slow threshold"
314 );
315 } else if let Some(level) = self.acquire_time_level {
316 private_tracing_dynamic_event!(
317 target: "sqlx::pool::acquire",
318 level,
319 aquired_after_secs = acquired_after.as_secs_f64(),
320 "acquired connection"
321 );
322 }
323
324 Ok(acquired)
325 }
326
327 pub(super) async fn connect(
328 self: &Arc<Self>,
329 deadline: Instant,
330 guard: DecrementSizeGuard<DB>,
331 ) -> Result<Floating<DB, Live<DB>>, Error> {
332 if self.is_closed() {
333 return Err(Error::PoolClosed);
334 }
335
336 let mut backoff = Duration::from_millis(10);
337 let max_backoff = deadline_as_timeout(deadline)? / 5;
338
339 loop {
340 let timeout = deadline_as_timeout(deadline)?;
341
342 // clone the connect options arc so it can be used without holding the RwLockReadGuard
343 // across an async await point
344 let connect_options = self
345 .connect_options
346 .read()
347 .expect("write-lock holder panicked")
348 .clone();
349
350 // result here is `Result<Result<C, Error>, TimeoutError>`
351 // if this block does not return, sleep for the backoff timeout and try again
352 match crate::rt::timeout(timeout, connect_options.connect()).await {
353 // successfully established connection
354 Ok(Ok(mut raw)) => {
355 // See comment on `PoolOptions::after_connect`
356 let meta = PoolConnectionMetadata {
357 age: Duration::ZERO,
358 idle_for: Duration::ZERO,
359 };
360
361 let res = if let Some(callback) = &self.options.after_connect {
362 callback(&mut raw, meta).await
363 } else {
364 Ok(())
365 };
366
367 match res {
368 Ok(()) => return Ok(Floating::new_live(raw, guard)),
369 Err(error) => {
370 tracing::error!(%error, "error returned from after_connect");
371 // The connection is broken, don't try to close nicely.
372 let _ = raw.close_hard().await;
373
374 // Fall through to the backoff.
375 }
376 }
377 }
378
379 // an IO error while connecting is assumed to be the system starting up
380 Ok(Err(Error::Io(e))) if e.kind() == std::io::ErrorKind::ConnectionRefused => (),
381
382 // We got a transient database error, retry.
383 Ok(Err(Error::Database(error))) if error.is_transient_in_connect_phase() => (),
384
385 // Any other error while connection should immediately
386 // terminate and bubble the error up
387 Ok(Err(e)) => return Err(e),
388
389 // timed out
390 Err(_) => return Err(Error::PoolTimedOut),
391 }
392
393 // If the connection is refused, wait in exponentially
394 // increasing steps for the server to come up,
395 // capped by a factor of the remaining time until the deadline
396 crate::rt::sleep(backoff).await;
397 backoff = cmp::min(backoff * 2, max_backoff);
398 }
399 }
400
401 /// Try to maintain `min_connections`, returning any errors (including `PoolTimedOut`).
402 pub async fn try_min_connections(self: &Arc<Self>, deadline: Instant) -> Result<(), Error> {
403 while self.size() < self.options.min_connections {
404 // Don't wait for a semaphore permit.
405 //
406 // If no extra permits are available then we shouldn't be trying to spin up
407 // connections anyway.
408 let Some(permit) = self.semaphore.try_acquire(1) else {
409 return Ok(());
410 };
411
412 // We must always obey `max_connections`.
413 let Some(guard) = self.try_increment_size(permit).ok() else {
414 return Ok(());
415 };
416
417 // We skip `after_release` since the connection was never provided to user code
418 // besides `after_connect`, if they set it.
419 self.release(self.connect(deadline, guard).await?);
420 }
421
422 Ok(())
423 }
424
425 /// Attempt to maintain `min_connections`, logging if unable.
426 pub async fn min_connections_maintenance(self: &Arc<Self>, deadline: Option<Instant>) {
427 let deadline = deadline.unwrap_or_else(|| {
428 // Arbitrary default deadline if the caller doesn't care.
429 Instant::now() + Duration::from_secs(300)
430 });
431
432 match self.try_min_connections(deadline).await {
433 Ok(()) => (),
434 Err(Error::PoolClosed) => (),
435 Err(Error::PoolTimedOut) => {
436 tracing::debug!("unable to complete `min_connections` maintenance before deadline")
437 }
438 Err(error) => tracing::debug!(%error, "error while maintaining min_connections"),
439 }
440 }
441 }
442
443 impl<DB: Database> Drop for PoolInner<DB> {
444 fn drop(&mut self) {
445 self.mark_closed();
446
447 if let Some(parent) = &self.options.parent_pool {
448 // Release the stolen permits.
449 parent.0.semaphore.release(self.semaphore.permits());
450 }
451 }
452 }
453
454 /// Returns `true` if the connection has exceeded `options.max_lifetime` if set, `false` otherwise.
455 pub(super) fn is_beyond_max_lifetime<DB: Database>(
456 live: &Live<DB>,
457 options: &PoolOptions<DB>,
458 ) -> bool {
459 options
460 .max_lifetime
461 .map_or(false, |max| live.created_at.elapsed() > max)
462 }
463
464 /// Returns `true` if the connection has exceeded `options.idle_timeout` if set, `false` otherwise.
465 fn is_beyond_idle_timeout<DB: Database>(idle: &Idle<DB>, options: &PoolOptions<DB>) -> bool {
466 options
467 .idle_timeout
468 .map_or(false, |timeout| idle.idle_since.elapsed() > timeout)
469 }
470
471 async fn check_idle_conn<DB: Database>(
472 mut conn: Floating<DB, Idle<DB>>,
473 options: &PoolOptions<DB>,
474 ) -> Result<Floating<DB, Live<DB>>, DecrementSizeGuard<DB>> {
475 if options.test_before_acquire {
476 // Check that the connection is still live
477 if let Err(error) = conn.ping().await {
478 // an error here means the other end has hung up or we lost connectivity
479 // either way we're fine to just discard the connection
480 // the error itself here isn't necessarily unexpected so WARN is too strong
481 tracing::info!(%error, "ping on idle connection returned error");
482 // connection is broken so don't try to close nicely
483 return Err(conn.close_hard().await);
484 }
485 }
486
487 if let Some(test) = &options.before_acquire {
488 let meta = conn.metadata();
489 match test(&mut conn.live.raw, meta).await {
490 Ok(false) => {
491 // connection was rejected by user-defined hook, close nicely
492 return Err(conn.close().await);
493 }
494
495 Err(error) => {
496 tracing::warn!(%error, "error from `before_acquire`");
497 // connection is broken so don't try to close nicely
498 return Err(conn.close_hard().await);
499 }
500
501 Ok(true) => {}
502 }
503 }
504
505 // No need to re-connect; connection is alive or we don't care
506 Ok(conn.into_live())
507 }
508
509 fn spawn_maintenance_tasks<DB: Database>(pool: &Arc<PoolInner<DB>>) {
510 // NOTE: use `pool_weak` for the maintenance tasks
511 // so they don't keep `PoolInner` from being dropped.
512 let pool_weak = Arc::downgrade(pool);
513
514 let period = match (pool.options.max_lifetime, pool.options.idle_timeout) {
515 (Some(it), None) | (None, Some(it)) => it,
516
517 (Some(a), Some(b)) => cmp::min(a, b),
518
519 (None, None) => {
520 if pool.options.min_connections > 0 {
521 crate::rt::spawn(async move {
522 if let Some(pool) = pool_weak.upgrade() {
523 pool.min_connections_maintenance(None).await;
524 }
525 });
526 }
527
528 return;
529 }
530 };
531
532 // Immediately cancel this task if the pool is closed.
533 let mut close_event = pool.close_event();
534
535 crate::rt::spawn(async move {
536 let _ = close_event
537 .do_until(async {
538 // If the last handle to the pool was dropped while we were sleeping
539 while let Some(pool) = pool_weak.upgrade() {
540 if pool.is_closed() {
541 return;
542 }
543
544 let next_run = Instant::now() + period;
545
546 // Go over all idle connections, check for idleness and lifetime,
547 // and if we have fewer than min_connections after reaping a connection,
548 // open a new one immediately. Note that other connections may be popped from
549 // the queue in the meantime - that's fine, there is no harm in checking more
550 for _ in 0..pool.num_idle() {
551 if let Some(conn) = pool.try_acquire() {
552 if is_beyond_idle_timeout(&conn, &pool.options)
553 || is_beyond_max_lifetime(&conn, &pool.options)
554 {
555 let _ = conn.close().await;
556 pool.min_connections_maintenance(Some(next_run)).await;
557 } else {
558 pool.release(conn.into_live());
559 }
560 }
561 }
562
563 // Don't hold a reference to the pool while sleeping.
564 drop(pool);
565
566 if let Some(duration) = next_run.checked_duration_since(Instant::now()) {
567 // `async-std` doesn't have a `sleep_until()`
568 crate::rt::sleep(duration).await;
569 } else {
570 // `next_run` is in the past, just yield.
571 crate::rt::yield_now().await;
572 }
573 }
574 })
575 .await;
576 });
577 }
578
579 /// RAII guard returned by `Pool::try_increment_size()` and others.
580 ///
581 /// Will decrement the pool size if dropped, to avoid semantically "leaking" connections
582 /// (where the pool thinks it has more connections than it does).
583 pub(in crate::pool) struct DecrementSizeGuard<DB: Database> {
584 pub(crate) pool: Arc<PoolInner<DB>>,
585 cancelled: bool,
586 }
587
588 impl<DB: Database> DecrementSizeGuard<DB> {
589 /// Create a new guard that will release a semaphore permit on-drop.
590 pub fn new_permit(pool: Arc<PoolInner<DB>>) -> Self {
591 Self {
592 pool,
593 cancelled: false,
594 }
595 }
596
597 pub fn from_permit(pool: Arc<PoolInner<DB>>, permit: AsyncSemaphoreReleaser<'_>) -> Self {
598 // here we effectively take ownership of the permit
599 permit.disarm();
600 Self::new_permit(pool)
601 }
602
603 /// Release the semaphore permit without decreasing the pool size.
604 ///
605 /// If the permit was stolen from the pool's parent, it will be returned to the child's semaphore.
606 fn release_permit(self) {
607 self.pool.semaphore.release(1);
608 self.cancel();
609 }
610
611 pub fn cancel(mut self) {
612 self.cancelled = true;
613 }
614 }
615
616 impl<DB: Database> Drop for DecrementSizeGuard<DB> {
617 fn drop(&mut self) {
618 if !self.cancelled {
619 self.pool.size.fetch_sub(1, Ordering::AcqRel);
620
621 // and here we release the permit we got on construction
622 self.pool.semaphore.release(1);
623 }
624 }
625 }