Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/pool.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Utilities to handle reusing connections.
5 //!
6 //! Creating a single new connection requires significant
7 //! memory allocations (about 50-60 KB, according to some tests).
8 //! Instead of allocating memory for a new connection, existing
9 //! memory can be reused by calling
10 //! [Connection::wipe()](`crate::connection::Connection::wipe()).
11 //!
12 //! On modern systems with reasonably performant allocators, the benefits of reusing
13 //! connections are reduced. Connection reuse is specifically intended for customers
14 //! who are sensitive to allocations or for whom allocations are more expensive.
15 //! Customers are encouraged to run their own benchmarks to determine the exact
16 //! performance benefit. As a starting point, a simple benchmark comparing allocation
17 //! against reuse can be found `bench/benches/connection_creation.rs`.
18 //!
19 //! The [`Pool`] trait allows applications to define an
20 //! [Object pool](https://en.wikipedia.org/wiki/Object_pool_pattern) that
21 //! wipes and stores connections after they are dropped.
22 //!
23 //! We also provide a basic Pool implementation, [`ConfigPool`], that
24 //! implements the pool as a [VecDeque](`std::collections::VecDeque`)
25 //! with a fixed maximum size.
26
27 use crate::{
28 config::Config,
29 connection::{Builder, Connection},
30 enums::Mode,
31 error::Error,
32 };
33 use std::{
34 collections::VecDeque,
35 ops::{Deref, DerefMut},
36 sync::{Arc, Mutex},
37 };
38
39 /// A connection produced by a [`Pool`].
40 ///
41 /// When dropped, returns ownership of the connection to
42 /// the pool that produced it by calling [`Pool::give`].
43 #[derive(Debug)]
44 pub struct PooledConnection<T: Pool = Arc<dyn Pool>> {
45 pool: T,
46 conn: Option<Connection>,
47 }
48
49 impl<T: Pool> AsRef<Connection> for PooledConnection<T> {
50 fn as_ref(&self) -> &Connection {
51 self.conn.as_ref().unwrap()
52 }
53 }
54
55 impl<T: Pool> AsMut<Connection> for PooledConnection<T> {
56 fn as_mut(&mut self) -> &mut Connection {
57 self.conn.as_mut().unwrap()
58 }
59 }
60
61 impl<T: Pool> Drop for PooledConnection<T> {
62 fn drop(&mut self) {
63 if let Some(conn) = self.conn.take() {
64 self.pool.give(conn);
65 }
66 }
67 }
68
69 impl<T: Pool> Deref for PooledConnection<T> {
70 type Target = Connection;
71
72 fn deref(&self) -> &Self::Target {
73 self.conn.as_ref().unwrap()
74 }
75 }
76
77 impl<T: Pool> DerefMut for PooledConnection<T> {
78 fn deref_mut(&mut self) -> &mut Self::Target {
79 self.conn.as_mut().unwrap()
80 }
81 }
82
83 impl<T: Pool + Clone> PooledConnection<T> {
84 pub fn new(pool: &T) -> Result<PooledConnection<T>, Error> {
85 pool.take().map(|conn| {
86 let conn = Some(conn);
87 let pool = pool.clone();
88 Self { pool, conn }
89 })
90 }
91 }
92
93 /// An object pool for wiping and reusing connection memory.
94 ///
95 /// Minimally, an implementation should call [`Connection::wipe()`]
96 /// during [`Self::give`].
97 pub trait Pool {
98 fn mode(&self) -> Mode;
99 fn take(&self) -> Result<Connection, Error>;
100 fn give(&self, conn: Connection);
101 }
102
103 impl Pool for Arc<dyn Pool> {
104 fn mode(&self) -> Mode {
105 self.as_ref().mode()
106 }
107 fn take(&self) -> Result<Connection, Error> {
108 self.as_ref().take()
109 }
110 fn give(&self, conn: Connection) {
111 self.as_ref().give(conn)
112 }
113 }
114
115 impl<T: Pool> Pool for Arc<T> {
116 fn mode(&self) -> Mode {
117 self.as_ref().mode()
118 }
119 fn take(&self) -> Result<Connection, Error> {
120 self.as_ref().take()
121 }
122 fn give(&self, conn: Connection) {
123 self.as_ref().give(conn)
124 }
125 }
126
127 /// A pool of Connections. Not a pool of Configs.
128 ///
129 /// Connections yielded from the pool will always be associated with `config`
130 /// from [ConfigPoolBuilder::new].
131 ///
132 /// For discussions about expected performance benefits see [self].
133 #[derive(Debug)]
134 pub struct ConfigPool {
135 mode: Mode,
136 config: Config,
137 pool: Mutex<VecDeque<Connection>>,
138 max_pool_size: usize,
139 }
140
141 pub type ConfigPoolRef = Arc<ConfigPool>;
142
143 /// Builder for [`ConfigPool`].
144 pub struct ConfigPoolBuilder(ConfigPool);
145 impl ConfigPoolBuilder {
146 pub fn new(mode: Mode, config: Config) -> Self {
147 Self(ConfigPool {
148 mode,
149 config,
150 pool: Mutex::new(VecDeque::new()),
151 max_pool_size: usize::MAX,
152 })
153 }
154
155 pub fn set_pool(&mut self, pool: VecDeque<Connection>) -> &mut Self {
156 self.0.pool = Mutex::new(pool);
157 self
158 }
159
160 /// The maximum size of the underlying [`VecDeque`].
161 ///
162 /// This is NOT the maximum connections that can be created.
163 /// When the number of connections created exceeds the `max_pool_size`,
164 /// excess reclaimed connections are dropped instead of stored
165 /// in the pool.
166 ///
167 /// If this is not specified, then the max pool size will be usize::MAX
168 pub fn set_max_pool_size(&mut self, max_pool_size: usize) -> &mut Self {
169 self.0.max_pool_size = max_pool_size;
170 self
171 }
172
173 pub fn build(self) -> Arc<ConfigPool> {
174 Arc::new(self.0)
175 }
176 }
177
178 impl ConfigPool {
179 pub fn pool_size(&self) -> usize {
180 self.pool.lock().map(|pool| pool.len()).unwrap_or(0)
181 }
182
183 pub fn is_poisoned(&self) -> bool {
184 self.pool.is_poisoned()
185 }
186 }
187
188 impl Pool for ConfigPool {
189 fn mode(&self) -> Mode {
190 self.mode
191 }
192
193 /// Get a connection.
194 ///
195 /// If connections are available in the pool, one will
196 /// be returned. Otherwise, a new connection will be created.
197 fn take(&self) -> Result<Connection, Error> {
198 let from_pool = match self.pool.lock() {
199 Ok(mut pool) => pool.pop_front(),
200 Err(_) => None,
201 };
202 let conn = match from_pool {
203 // Wiping a connection doesn't wipe the config, but callbacks might
204 // have swapped the config so we reset it anyways.
205 Some(mut conn) => {
206 conn.set_config(self.config.clone())?;
207 conn
208 }
209 // Create a new connection with the stored config.
210 None => self.config.build_connection(self.mode)?,
211 };
212 Ok(conn)
213 }
214
215 /// Recycle a connection.
216 ///
217 /// The connection is wiped and returned to the pool
218 /// if space is available.
219 fn give(&self, mut conn: Connection) {
220 let wiped = conn.wipe().is_ok();
221 if let Ok(mut pool) = self.pool.lock() {
222 if pool.len() < self.max_pool_size && wiped {
223 pool.push_back(conn);
224 }
225 }
226 }
227 }
228
229 #[cfg(test)]
230 mod tests {
231 use super::*;
232 use crate::{
233 callbacks::ClientHelloCallback,
234 config::{self, Config},
235 connection, error,
236 testing::TestPair,
237 };
238
239 #[test]
240 fn config_pool_single_connection() -> Result<(), Box<dyn std::error::Error>> {
241 let pool = ConfigPoolBuilder::new(Mode::Server, Config::default()).build();
242
243 // Repeatedly checkout the same connection
244 assert_eq!(pool.pool_size(), 0);
245 for _ in 0..5 {
246 let _conn = PooledConnection::new(&pool)?;
247 assert_eq!(pool.pool_size(), 0);
248 }
249 assert_eq!(pool.pool_size(), 1);
250 Ok(())
251 }
252
253 #[test]
254 fn config_pool_multiple_connections() -> Result<(), Box<dyn std::error::Error>> {
255 let pool = ConfigPoolBuilder::new(Mode::Server, Config::default()).build();
256
257 // We need to hold onto connections so that they're not
258 // immediately reclaimed by the pool.
259 let mut conns = VecDeque::new();
260
261 // Checkout multiple connections
262 const COUNT: usize = 25;
263 for _ in 0..COUNT {
264 conns.push_back(PooledConnection::new(&pool)?);
265 assert_eq!(pool.pool_size(), 0);
266 }
267 assert_eq!(conns.len(), COUNT);
268
269 // Drop all outstanding connections, returning them to the pool
270 conns.clear();
271 assert_eq!(pool.pool_size(), COUNT);
272
273 // Reuse a subset of the connections
274 const SUBSET_COUNT: usize = COUNT / 2;
275 for i in 1..=SUBSET_COUNT {
276 conns.push_back(PooledConnection::new(&pool)?);
277 // The pool should drain as we reuse connections.
278 assert_eq!(pool.pool_size(), COUNT - i);
279 }
280 assert_eq!(conns.len(), SUBSET_COUNT);
281 assert_eq!(pool.pool_size(), COUNT - SUBSET_COUNT);
282
283 // Drop all outstanding connections, returning them to the pool
284 conns.clear();
285 assert_eq!(pool.pool_size(), COUNT);
286
287 Ok(())
288 }
289
290 #[test]
291 fn config_pool_with_max_size() -> Result<(), Box<dyn std::error::Error>> {
292 const POOL_MAX_SIZE: usize = 11;
293 let mut pool = ConfigPoolBuilder::new(Mode::Server, Config::default());
294 pool.set_max_pool_size(POOL_MAX_SIZE);
295 let pool = pool.build();
296
297 // We need to hold onto connections so that they're not
298 // immediately reclaimed by the pool.
299 let mut conns = VecDeque::new();
300
301 // Create more connections than the pools can hold
302 const COUNT: usize = 25;
303 for _ in 0..COUNT {
304 conns.push_back(PooledConnection::new(&pool)?);
305 }
306 assert_eq!(conns.len(), COUNT);
307
308 // Drop all outstanding connections, returning them to the pools
309 // The pool should now hold its maximum.
310 conns.clear();
311 assert_eq!(pool.pool_size(), POOL_MAX_SIZE);
312
313 Ok(())
314 }
315
316 #[test]
317 fn non_generic_pool() -> Result<(), Box<dyn std::error::Error>> {
318 let config_pool = ConfigPoolBuilder::new(Mode::Server, Config::default()).build();
319 // Note the unwieldy type parameters on PooledConnection here.
320 let _: PooledConnection<ConfigPoolRef> = PooledConnection::new(&config_pool)?;
321 // To avoid specifying the generic type parameters on PooledConnection,
322 // the pool can be converted to an Arc<dyn Pool>.
323 let pool: Arc<dyn Pool> = config_pool;
324 // Note no generic type parameters on PooledConnection here.
325 let _: PooledConnection = PooledConnection::new(&pool)?;
326 Ok(())
327 }
328
329 #[test]
330 fn dereferencing_pooled_connection() -> Result<(), Box<dyn std::error::Error>> {
331 let config_pool = ConfigPoolBuilder::new(Mode::Server, Config::default()).build();
332
333 let pooled_conn: PooledConnection<ConfigPoolRef> = PooledConnection::new(&config_pool)?;
334 let conn = pooled_conn.deref();
335 assert_eq!(pooled_conn.config(), conn.config());
336
337 let mut mut_pooled_conn: PooledConnection<ConfigPoolRef> =
338 PooledConnection::new(&config_pool)?;
339 let waker = futures_test::task::new_count_waker().0;
340 mut_pooled_conn.set_waker(Some(&waker))?;
341 assert!(mut_pooled_conn.waker().unwrap().will_wake(&waker));
342
343 Ok(())
344 }
345
346 // A yielded connection should always be associated with `config` in the
347 // config pool, even if the connection's config is swapped by callbacks.
348 #[test]
349 fn yielded_connection_associated_config() -> Result<(), error::Error> {
350 fn associated_config_has_ch_callback(conn: &connection::Connection) -> bool {
351 conn.config()
352 .unwrap()
353 .context()
354 .client_hello_callback
355 .is_some()
356 }
357
358 struct ConfigSwapCallback(Config);
359 impl ClientHelloCallback for ConfigSwapCallback {
360 fn on_client_hello(
361 &self,
362 connection: &mut Connection,
363 ) -> crate::callbacks::ConnectionFutureResult {
364 connection.set_config(self.0.clone())?;
365 Ok(None)
366 }
367 }
368
369 let empty_config = config::Builder::new().build()?;
370
371 let mut config_with_callback = config::Builder::new();
372 let dead_end_callback = ConfigSwapCallback(empty_config);
373 config_with_callback.set_client_hello_callback(dead_end_callback)?;
374 let config_with_callback = config_with_callback.build()?;
375
376 let config_with_pooled_connections =
377 ConfigPoolBuilder::new(Mode::Server, config_with_callback).build();
378
379 let server_from_pool = config_with_pooled_connections.take()?;
380 let client = Connection::new_client();
381 let mut pair = TestPair::from_connections(client, server_from_pool);
382
383 assert!(associated_config_has_ch_callback(&pair.server));
384 assert!(pair.handshake().is_err());
385 assert!(!associated_config_has_ch_callback(&pair.server));
386
387 config_with_pooled_connections.give(pair.server);
388
389 let server_from_pool = config_with_pooled_connections.take()?;
390 // reused connection once again has callback
391 assert!(associated_config_has_ch_callback(&server_from_pool));
392 config_with_pooled_connections.give(server_from_pool);
393
394 // assert that there is only a single connection that was getting reused
395 assert_eq!(config_with_pooled_connections.pool_size(), 1);
396 Ok(())
397 }
398 }