Skip to content

Commit 2be94a9

Browse files
committed
WIP feat: integrate sharding into pool
1 parent fb7c77b commit 2be94a9

6 files changed

Lines changed: 168 additions & 17 deletions

File tree

Cargo.lock

Lines changed: 14 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

sqlx-core/Cargo.toml

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,22 @@ hashbrown = "0.15.0"
9494
ease-off = { workspace = true, features = ["futures"] }
9595
pin-project-lite = "0.2.14"
9696

97-
[dependencies.parking_lot]
98-
version = "0.12.4"
97+
# N.B. we don't actually utilize spinlocks, we just need a `Mutex` type with a few requirements:
98+
# * Guards that are `Send` (so `parking_lot` and `std::sync` are non-starters)
99+
# * Guards that can use `Arc` and so don't borrow (which is provided by `lock_api`)
100+
#
101+
# Where we actually use this (in `sqlx-core/src/pool/shard.rs`), we don't rely on the mutex itself for anything but
102+
# safe shared mutability. The `Shard` structure has its own synchronization, and only uses `Mutex::try_lock()`.
103+
#
104+
# We *could* use either `tokio::sync::Mutex` or `async_lock::Mutex` for this, but those have all the code for the
105+
# async support, which we don't need.
106+
[dependencies.spin]
107+
version = "0.10.0"
108+
default-features = false
109+
features = ["mutex", "lock_api", "spin_mutex"]
110+
111+
[dependencies.lock_api]
112+
version = "0.4.13"
99113
features = ["arc_lock"]
100114

101115
[dev-dependencies]

sqlx-core/src/pool/connect.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,11 @@ pub trait PoolConnector<DB: Database>: Send + Sync + 'static {
220220
) -> impl Future<Output = crate::Result<DB::Connection>> + Send + '_;
221221
}
222222

223+
/// # Note: Future Changes (FIXME)
224+
/// This could theoretically be replaced with an impl over `AsyncFn` to allow lending closures,
225+
/// except we have no way to put the `Send` bound on the returned future.
226+
///
227+
/// We need Return Type Notation for that: https://github.com/rust-lang/rust/pull/138424
223228
impl<DB, F, Fut> PoolConnector<DB> for F
224229
where
225230
DB: Database,

sqlx-core/src/pool/inner.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use std::task::ready;
1313
use crate::logger::private_level_filter_to_trace_level;
1414
use crate::pool::connect::{ConnectPermit, ConnectionCounter, ConnectionId, DynConnector};
1515
use crate::pool::idle::IdleQueue;
16+
use crate::pool::shard::Sharded;
1617
use crate::rt::JoinHandle;
1718
use crate::{private_tracing_dynamic_event, rt};
1819
use either::Either;
@@ -24,6 +25,7 @@ use tracing::Level;
2425
pub(crate) struct PoolInner<DB: Database> {
2526
pub(super) connector: DynConnector<DB>,
2627
pub(super) counter: ConnectionCounter,
28+
pub(super) sharded: Sharded<DB::Connection>,
2729
pub(super) idle: IdleQueue<DB>,
2830
is_closed: AtomicBool,
2931
pub(super) on_closed: event_listener::Event,
@@ -40,6 +42,7 @@ impl<DB: Database> PoolInner<DB> {
4042
let pool = Self {
4143
connector: DynConnector::new(connector),
4244
counter: ConnectionCounter::new(),
45+
sharded: Sharded::new(options.max_connections, options.shards),
4346
idle: IdleQueue::new(options.fair, options.max_connections),
4447
is_closed: AtomicBool::new(false),
4548
on_closed: event_listener::Event::new(),

sqlx-core/src/pool/options.rs

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use crate::pool::{Pool, PoolConnector};
77
use futures_core::future::BoxFuture;
88
use log::LevelFilter;
99
use std::fmt::{self, Debug, Formatter};
10+
use std::num::NonZero;
1011
use std::sync::Arc;
1112
use std::time::{Duration, Instant};
1213

@@ -68,6 +69,7 @@ pub struct PoolOptions<DB: Database> {
6869
>,
6970
>,
7071
pub(crate) max_connections: usize,
72+
pub(crate) shards: NonZero<usize>,
7173
pub(crate) acquire_time_level: LevelFilter,
7274
pub(crate) acquire_slow_level: LevelFilter,
7375
pub(crate) acquire_slow_threshold: Duration,
@@ -91,6 +93,7 @@ impl<DB: Database> Clone for PoolOptions<DB> {
9193
before_acquire: self.before_acquire.clone(),
9294
after_release: self.after_release.clone(),
9395
max_connections: self.max_connections,
96+
shards: self.shards,
9497
acquire_time_level: self.acquire_time_level,
9598
acquire_slow_threshold: self.acquire_slow_threshold,
9699
acquire_slow_level: self.acquire_slow_level,
@@ -143,6 +146,7 @@ impl<DB: Database> PoolOptions<DB> {
143146
// A production application will want to set a higher limit than this.
144147
max_connections: 10,
145148
min_connections: 0,
149+
shards: NonZero::<usize>::MIN,
146150
// Logging all acquires is opt-in
147151
acquire_time_level: LevelFilter::Off,
148152
// Default to warning, because an acquire timeout will be an error
@@ -206,6 +210,58 @@ impl<DB: Database> PoolOptions<DB> {
206210
self.min_connections
207211
}
208212

213+
/// Set the number of shards to split the internal structures into.
214+
///
215+
/// The default value is dynamically determined based on the configured number of worker threads
216+
/// in the current runtime (if that information is available),
217+
/// or [`std::thread::available_parallelism()`],
218+
/// or 1 otherwise.
219+
///
220+
/// Each shard is assigned an equal share of [`max_connections`][Self::max_connections]
221+
/// and its own queue of tasks waiting to acquire a connection.
222+
///
223+
/// Then, when accessing the pool, each thread selects a "local" shard based on its
224+
/// [thread ID][std::thread::Thread::id]<sup>1</sup>.
225+
///
226+
/// If the number of shards equals the number of threads (which they do by default),
227+
/// and worker threads are spawned sequentially (which they generally are),
228+
/// each thread should access a different shard, which should significantly reduce
229+
/// cache coherence overhead on multicore systems.
230+
///
231+
/// If the number of shards does not evenly divide `max_connections`,
232+
/// the implementation makes a best-effort to distribute them as evenly as possible
233+
/// (if `remainder = max_connections % shards` and `remainder != 0`,
234+
/// then `remainder` shards will get one additional connection each).
235+
///
236+
/// The implementation then clamps the number of connections in a shard to the range `[1, 64]`.
237+
///
238+
/// ### Details
239+
/// When a task calls [`Pool::acquire()`] (or any other method that calls `acquire()`),
240+
/// it will first attempt to acquire a connection from its thread-local shard, or lock an empty
241+
/// slot to open a new connection (acquiring an idle connection and opening a new connection
242+
/// happen concurrently to minimize acquire time).
243+
///
244+
/// Failing that, it joins the wait list on the shard. Released connections are passed to
245+
/// waiting tasks in a first-come, first-serve order per shard.
246+
///
247+
/// If the task cannot acquire a connection after a short delay,
248+
/// it tries to acquire a connection from another shard.
249+
///
250+
/// If the task _still_ cannot acquire a connection after a longer delay,
251+
/// it joins a global wait list. Tasks in the global wait list are the highest priority
252+
/// for released connections, implementing a kind of eventual fairness.
253+
///
254+
/// <sup>1</sup> because, as of writing, [`std::thread::ThreadId::as_u64`] is unstable,
255+
/// the current implementation assigns each thread its own sequential ID in a `thread_local!()`.
256+
pub fn shards(mut self, shards: NonZero<usize>) -> Self {
257+
self.shards = shards;
258+
self
259+
}
260+
261+
pub fn get_shards(&self) -> usize {
262+
self.shards.get()
263+
}
264+
209265
/// Enable logging of time taken to acquire a connection from the connection pool via
210266
/// [`Pool::acquire()`].
211267
///
@@ -572,3 +628,28 @@ impl<DB: Database> Debug for PoolOptions<DB> {
572628
.finish()
573629
}
574630
}
631+
632+
fn default_shards() -> NonZero<usize> {
633+
#[cfg(feature = "_rt-tokio")]
634+
if let Ok(rt) = tokio::runtime::Handle::try_current() {
635+
return rt
636+
.metrics()
637+
.num_workers()
638+
.try_into()
639+
.unwrap_or(NonZero::<usize>::MIN);
640+
}
641+
642+
#[cfg(feature = "_rt-async-std")]
643+
if let Some(val) = std::env::var("ASYNC_STD_THREAD_COUNT")
644+
.ok()
645+
.and_then(|s| s.parse())
646+
{
647+
return val;
648+
}
649+
650+
if let Ok(val) = std::thread::available_parallelism() {
651+
return val;
652+
}
653+
654+
NonZero::<usize>::MIN
655+
}

sqlx-core/src/pool/shard.rs

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,27 @@
11
use event_listener::{Event, IntoNotification};
2-
use parking_lot::Mutex;
32
use std::future::Future;
3+
use std::num::NonZero;
44
use std::pin::pin;
55
use std::sync::atomic::{AtomicUsize, Ordering};
66
use std::sync::Arc;
77
use std::task::Poll;
88
use std::time::Duration;
99
use std::{array, iter};
1010

11+
use spin::lock_api::Mutex;
12+
1113
type ShardId = usize;
1214
type ConnectionIndex = usize;
1315

1416
/// Delay before a task waiting in a call to `acquire()` enters the global wait queue.
1517
///
1618
/// We want tasks to acquire from their local shards where possible, so they don't enter
1719
/// the global queue immediately.
18-
const GLOBAL_QUEUE_DELAY: Duration = Duration::from_millis(5);
20+
const GLOBAL_QUEUE_DELAY: Duration = Duration::from_millis(10);
21+
22+
/// Delay before attempting to acquire from a non-local shard,
23+
/// as well as the backoff when iterating through shards.
24+
const NON_LOCAL_ACQUIRE_DELAY: Duration = Duration::from_micros(100);
1925

2026
pub struct Sharded<T> {
2127
shards: Box<[ArcShard<T>]>,
@@ -29,11 +35,10 @@ struct Global<T> {
2935
disconnect_event: Event<LockGuard<T>>,
3036
}
3137

32-
type ArcMutexGuard<T> = parking_lot::ArcMutexGuard<parking_lot::RawMutex, Option<T>>;
38+
type ArcMutexGuard<T> = lock_api::ArcMutexGuard<spin::Mutex<()>, Option<T>>;
3339

3440
pub struct LockGuard<T> {
35-
// `Option` allows us to drop the guard before sending the notification.
36-
// Otherwise, if the receiver wakes too quickly, it might fail to lock the mutex.
41+
// `Option` allows us to take the guard in the drop handler.
3742
locked: Option<ArcMutexGuard<T>>,
3843
shard: ArcShard<T>,
3944
index: ConnectionIndex,
@@ -73,13 +78,13 @@ const MAX_SHARD_SIZE: usize = if usize::BITS > 64 {
7378
};
7479

7580
impl<T> Sharded<T> {
76-
pub fn new(connections: usize, shards: usize) -> Sharded<T> {
81+
pub fn new(connections: usize, shards: NonZero<usize>) -> Sharded<T> {
7782
let global = Arc::new(Global {
7883
unlock_event: Event::with_tag(),
7984
disconnect_event: Event::with_tag(),
8085
});
8186

82-
let shards = Params::calc(connections, shards)
87+
let shards = Params::calc(connections, shards.get())
8388
.shard_sizes()
8489
.enumerate()
8590
.map(|(shard_id, size)| Shard::new(shard_id, size, global.clone()))
@@ -89,8 +94,28 @@ impl<T> Sharded<T> {
8994
}
9095

9196
pub async fn acquire(&self, connected: bool) -> LockGuard<T> {
92-
let mut acquire_local =
93-
pin!(self.shards[thread_id() % self.shards.len()].acquire(connected));
97+
if self.shards.len() == 1 {
98+
return self.shards[0].acquire(connected).await;
99+
}
100+
101+
let thread_id = current_thread_id();
102+
103+
let mut acquire_local = pin!(self.shards[thread_id % self.shards.len()].acquire(connected));
104+
105+
let mut acquire_nonlocal = pin!(async {
106+
let mut next_shard = thread_id;
107+
108+
loop {
109+
crate::rt::sleep(NON_LOCAL_ACQUIRE_DELAY).await;
110+
111+
// Choose shards pseudorandomly by multiplying with a (relatively) large prime.
112+
next_shard = (next_shard.wrapping_mul(547)) % self.shards.len();
113+
114+
if let Some(locked) = self.shards[next_shard].try_acquire(connected) {
115+
return locked;
116+
}
117+
}
118+
});
94119

95120
let mut acquire_global = pin!(async {
96121
crate::rt::sleep(GLOBAL_QUEUE_DELAY).await;
@@ -113,6 +138,10 @@ impl<T> Sharded<T> {
113138
return Poll::Ready(locked);
114139
}
115140

141+
if let Poll::Ready(locked) = acquire_nonlocal.as_mut().poll(cx) {
142+
return Poll::Ready(locked);
143+
}
144+
116145
if let Poll::Ready(locked) = acquire_global.as_mut().poll(cx) {
117146
return Poll::Ready(locked);
118147
}
@@ -125,6 +154,9 @@ impl<T> Sharded<T> {
125154

126155
impl<T> Shard<T, [Arc<Mutex<Option<T>>>]> {
127156
fn new(shard_id: ShardId, len: usize, global: Arc<Global<T>>) -> Arc<Self> {
157+
// There's no way to create DSTs like this, in `std::sync::Arc`, on stable.
158+
//
159+
// Instead, we coerce from an array.
128160
macro_rules! make_array {
129161
($($n:literal),+) => {
130162
match len {
@@ -206,6 +238,8 @@ impl<T> Shard<T, [Arc<Mutex<Option<T>>>]> {
206238

207239
impl Params {
208240
fn calc(connections: usize, mut shards: usize) -> Params {
241+
assert_ne!(shards, 0);
242+
209243
let mut shard_size = connections / shards;
210244
let mut remainder = connections % shards;
211245

@@ -217,7 +251,11 @@ impl Params {
217251
} else if shard_size >= MAX_SHARD_SIZE {
218252
let new_shards = connections.div_ceil(MAX_SHARD_SIZE);
219253

220-
tracing::debug!(connections, shards, "clamping shard count to {new_shards}");
254+
tracing::debug!(
255+
connections,
256+
shards,
257+
"shard size exceeds {MAX_SHARD_SIZE}, clamping shard count to {new_shards}"
258+
);
221259

222260
shards = new_shards;
223261
shard_size = connections / shards;
@@ -239,7 +277,7 @@ impl Params {
239277
}
240278
}
241279

242-
fn thread_id() -> usize {
280+
fn current_thread_id() -> usize {
243281
// FIXME: this can be replaced when this is stabilized:
244282
// https://doc.rust-lang.org/stable/std/thread/struct.ThreadId.html#method.as_u64
245283
static THREAD_ID: AtomicUsize = AtomicUsize::new(0);

0 commit comments

Comments
 (0)