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
//! Outer pooled-client type and slot-selection logic.
use std::{net::SocketAddr, sync::Arc};
use bb8::Pool;
use bincode::Encode;
use tokio::task::JoinHandle;
use super::{
ClientPoolConfig,
churn::{PoolTaskChurnCounts, PoolTaskChurnObserver},
core::PoolCore,
handle::PoolHandle,
lease::PooledClientLease,
manager::WireframeConnectionManager,
scheduler::{self, SchedulerHandle},
slot::PoolSlot,
};
use crate::{
client::{ClientError, connect_parts::ClientBuildParts},
serializer::Serializer,
};
/// Pool of configured slots that create physical wireframe connections on
/// demand.
pub struct WireframeClientPool<S, P = (), C = ()>
where
S: Serializer + Clone + Send + Sync + 'static,
P: Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
/// Shared fixed physical slots retained by every live lease.
core: Arc<PoolCore<S, P, C>>,
/// Cloneable command handle onto the pool's single scheduler task.
scheduler: SchedulerHandle<S, P, C>,
/// Join handle used by [`Self::close`] to await scheduler termination.
task: JoinHandle<()>,
}
impl<S, P, C> WireframeClientPool<S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
/// Build the configured slots; physical connections are created on demand
/// when a lease checks out a slot.
pub(crate) async fn connect(
addr: SocketAddr,
pool_config: ClientPoolConfig,
parts: ClientBuildParts<S, P, C>,
) -> Result<Self, ClientError> {
let fairness_policy = pool_config.fairness_policy_value();
let max_waiters = pool_config.max_waiters_value();
let mut slots = Vec::with_capacity(pool_config.pool_size_value());
for _ in 0..pool_config.pool_size_value() {
let manager = WireframeConnectionManager::new(addr, parts.clone());
let bb8_pool = Pool::builder()
.max_size(1)
.idle_timeout(Some(pool_config.idle_timeout_value()))
.reaper_rate(pool_config.idle_timeout_value())
.build(manager)
.await?;
slots.push(PoolSlot::new(
bb8_pool,
pool_config.max_in_flight_per_socket_value(),
pool_config.idle_timeout_value(),
));
}
let core = Arc::new(PoolCore::new(slots.into_boxed_slice()));
let churn = Arc::new(PoolTaskChurnCounts::default());
let (scheduler, task) = scheduler::start(&core, fairness_policy, max_waiters, churn);
Ok(Self {
core,
scheduler,
task,
})
}
/// Take a read-only handle onto this pool's task-churn counters.
///
/// The counters are scoped to this pool, so a delta between two snapshots
/// can only be attributed to work done on this pool. They are not shared
/// process-wide: a benchmark that reads a delta while an unrelated test
/// drives a different pool sees only its own pool's activity.
///
/// Taking an observer is passive — it performs no acquire and spawns no
/// task — so a bracket built from snapshots cannot perturb what it
/// measures.
///
/// # Examples
///
/// ```no_run
/// # use std::net::SocketAddr;
/// use wireframe::client::{ClientPoolConfig, WireframeClient};
///
/// # async fn demo(addr: SocketAddr) -> Result<(), wireframe::client::ClientError> {
/// let pool = WireframeClient::builder()
/// .connect_pool(addr, ClientPoolConfig::default())
/// .await?;
/// let observer = pool.task_churn_observer();
/// let before = observer.snapshot();
///
/// let lease = pool.acquire().await?;
/// drop(lease);
///
/// let churn = observer.snapshot().since(before);
/// // The pool spawned its scheduler when it was built, so acquiring and
/// // releasing a lease spawns nothing at all.
/// assert_eq!(churn.scheduler_spawns, 0);
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn task_churn_observer(&self) -> PoolTaskChurnObserver {
PoolTaskChurnObserver::new(self.scheduler.churn())
}
/// Create a stable logical-session handle governed by the pool scheduler.
///
/// Prefer a `PoolHandle` when one logical session repeatedly acquires
/// pooled leases and should receive fair turns relative to other blocked
/// sessions.
///
/// # Examples
///
/// ```no_run
/// # use std::net::SocketAddr;
/// use wireframe::client::{ClientPoolConfig, PoolHandle, WireframeClient};
///
/// # async fn demo(addr: SocketAddr) -> Result<(), wireframe::client::ClientError> {
/// let pool = WireframeClient::builder()
/// .connect_pool(addr, ClientPoolConfig::default())
/// .await?;
/// let mut handle: PoolHandle<_, _, _> = pool.handle();
/// let lease = handle.acquire().await?;
/// drop(lease);
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn handle(&self) -> PoolHandle<S, P, C> {
let handle_id = self.scheduler.allocate_handle_id();
PoolHandle::new(self.scheduler.clone(), handle_id)
}
/// Acquire one pooled-client lease.
///
/// # Errors
///
/// Returns [`ClientError`] if permit acquisition or pooled checkout fails.
pub async fn acquire(&self) -> Result<PooledClientLease<S, P, C>, ClientError> {
let mut handle = self.handle();
handle.acquire().await
}
/// Report how many physical slots this pool owns.
///
/// The count is fixed at construction; it is exposed through the
/// `test-support` feature so behavioural tests can assert that they really
/// exercised a multi-slot pool.
///
/// # Examples
///
/// ```no_run
/// # use std::net::SocketAddr;
/// use wireframe::client::{ClientPoolConfig, WireframeClient};
///
/// # async fn demo(addr: SocketAddr) -> Result<(), wireframe::client::ClientError> {
/// let pool = WireframeClient::builder()
/// .connect_pool(addr, ClientPoolConfig::default().pool_size(3))
/// .await?;
/// assert_eq!(pool.pool_size(), 3);
/// # Ok(())
/// # }
/// ```
#[cfg(any(test, feature = "test-support"))]
#[must_use]
pub fn pool_size(&self) -> usize { self.core.pool_size() }
/// Close the pool to new acquisitions and await scheduler shutdown.
///
/// Shutdown is published before this method returns: an outstanding handle
/// that keeps the shared pool state alive still observes it, and any later
/// acquisition fails with [`ClientError::PoolClosed`] instead of taking
/// capacity mid-teardown. Every acquisition already queued is resolved with
/// the same error rather than being left parked.
///
/// The pool's single scheduler task is joined before this returns, so a
/// caller can rely on the task being gone afterwards. Dropping the sockets
/// is still deferred: a lease acquired before close is not revoked, and it
/// keeps the pool core and its slots alive until it is dropped. The lease
/// does not pin the sockets themselves: each operation returns its socket
/// to `bb8`, whose reaper can close an idle socket before the lease is
/// dropped, even while a reply is still pending.
///
/// # Examples
///
/// ```no_run
/// # use std::net::SocketAddr;
/// use wireframe::client::{ClientError, ClientPoolConfig, WireframeClient};
///
/// # async fn demo(addr: SocketAddr) -> Result<(), Box<dyn std::error::Error>> {
/// let pool = WireframeClient::builder()
/// .connect_pool(addr, ClientPoolConfig::default())
/// .await?;
/// let mut handle = pool.handle();
/// pool.close().await;
///
/// let error = match handle.acquire().await {
/// Ok(_lease) => panic!("closed pool must refuse"),
/// Err(error) => error,
/// };
/// assert!(matches!(error, ClientError::PoolClosed));
/// # Ok(())
/// # }
/// ```
pub async fn close(self) {
let Self {
core,
scheduler,
task,
} = self;
scheduler.mark_closed();
// `PoolCore::shutdown` notifies the scheduler's biased shutdown arm,
// which drains queued and buffered acquisitions before the task ends.
// Closing the mailbox by dropping the last sender is the fallback
// signal when every handle has already gone; dropping the core
// reference here lets teardown proceed once the task releases its own.
core.shutdown();
drop(scheduler);
drop(core);
if let Err(error) = task.await {
tracing::error!(%error, "client pool scheduler task terminated with a join error");
}
}
}
impl<S, P, C> PooledClientLease<S, P, C>
where
S: Serializer + Clone + Send + Sync + 'static,
P: bincode::Encode + Clone + Send + Sync + 'static,
C: Send + 'static,
{
/// Report which physical slot this lease was granted from.
///
/// The identifier is a stable index within this lease's pool, not a socket
/// address or connection identifier. It is exposed through the
/// `test-support` feature so behavioural tests can assert rotation order
/// through the public acquisition API.
///
/// # Examples
///
/// ```no_run
/// # use std::net::SocketAddr;
/// use wireframe::client::{ClientPoolConfig, PooledClientLease, WireframeClient};
///
/// # async fn demo(addr: SocketAddr) -> Result<(), wireframe::client::ClientError> {
/// let pool = WireframeClient::builder()
/// .connect_pool(addr, ClientPoolConfig::default().pool_size(2))
/// .await?;
/// let first = pool.acquire().await?;
/// let second = pool.acquire().await?;
/// assert_ne!(first.slot_id(), second.slot_id());
/// # Ok(())
/// # }
/// ```
#[cfg(any(test, feature = "test-support"))]
#[must_use]
pub const fn slot_id(&self) -> usize { self.selected_slot_index() }
}
#[cfg(test)]
#[path = "client_pool_tests.rs"]
mod tests;