tightbeam-rs 0.8.0

A secure, high-performance messaging protocol library
Documentation
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
//! Connection pooling for transport layer

use core::hash::Hash;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::time::Duration;

#[cfg(feature = "std")]
use std::collections::{HashMap, VecDeque};
#[cfg(feature = "std")]
use std::sync::{Arc, RwLock, RwLockWriteGuard};
#[cfg(feature = "std")]
use std::time::Instant;

use crate::crypto::profiles::CryptoProvider;
use crate::crypto::{key::SigningKeyProvider, x509::CertificateSpec};
use crate::transport::client::GenericClient;
use crate::transport::error::{TransportError, TransportFailure};
use crate::transport::handshake::HandshakeKeyManager;
use crate::transport::protocols::{PersistentConnection, Protocol};
use crate::transport::MessageCollector;
use crate::transport::{TransportResult, X509ClientConfig};

#[cfg(feature = "aes-gcm")]
use crate::crypto::profiles::DefaultCryptoProvider;
#[cfg(feature = "x509")]
use crate::crypto::x509::store::CertificateTrust;
#[cfg(feature = "x509")]
use crate::crypto::x509::Certificate;
#[cfg(not(feature = "x509"))]
use crate::transport::client::ClientBuilder;
#[cfg(feature = "transport-policy")]
use crate::transport::policy::PolicyConf;
#[cfg(feature = "transport-policy")]
use crate::transport::MessageEmitter;

/// Builder trait for connection configuration
///
/// Implemented by both ClientBuilder (for direct connections) and
/// ConnectionPoolBuilder (for pooled connections), enabling unified builder API.
pub trait ConnectionBuilder<P: Protocol>: Sized {
	/// The type returned by build()
	type Output;

	/// Configure timeout for operations
	fn with_timeout(self, timeout: Duration) -> Self;

	/// Configure trust store for server certificate validation
	#[cfg(feature = "x509")]
	fn with_trust_store(self, store: Arc<dyn CertificateTrust>) -> Self;

	/// Configure client identity for mutual TLS
	#[cfg(feature = "x509")]
	fn with_client_identity(self, cert: CertificateSpec, key: Arc<dyn SigningKeyProvider>) -> TransportResult<Self>;

	/// Build the configured builder/pool (sync)
	fn build(self) -> Self::Output;
}

/// Configuration for connection pool
#[derive(Clone, Debug)]
pub struct PoolConfig {
	/// Optional idle timeout for connections
	/// None means connections never expire
	pub idle_timeout: Option<Duration>,
	/// Maximum total connections in the pool (default: 64)
	pub max_connections: usize,
}

impl Default for PoolConfig {
	fn default() -> Self {
		Self { idle_timeout: None, max_connections: 64 }
	}
}

#[cfg(feature = "x509")]
#[derive(Clone)]
/// Client authentication bundle kept behind Arc for zero-copy reuse.
struct ClientIdentity<C: CryptoProvider = DefaultCryptoProvider> {
	certificate: Arc<Certificate>,
	key: Arc<HandshakeKeyManager<C>>,
}

#[cfg(feature = "x509")]
#[derive(Clone, Default)]
/// Shared TLS assets reused across pooled connections without reallocations.
struct PoolTlsConfig<C: CryptoProvider = DefaultCryptoProvider> {
	trust_store: Option<Arc<dyn CertificateTrust>>,
	client_identity: Option<ClientIdentity<C>>,
}

#[cfg(feature = "x509")]
impl<C: CryptoProvider + Send + Sync + 'static> PoolTlsConfig<C> {
	fn set_trust_store(&mut self, store: Arc<dyn CertificateTrust>) {
		self.trust_store = Some(store);
	}

	fn set_client_identity(&mut self, cert: Certificate, key: HandshakeKeyManager<C>) {
		self.client_identity = Some(ClientIdentity { certificate: Arc::new(cert), key: Arc::new(key) });
	}

	fn apply<Pro>(&self, transport: Pro::Transport) -> Pro::Transport
	where
		Pro: Protocol,
		Pro::Transport: MessageEmitter + MessageCollector + PolicyConf + X509ClientConfig<CryptoProvider = C>,
	{
		let mut configured = transport;
		if let Some(store) = &self.trust_store {
			configured = configured.with_trust_store(Arc::clone(store));
		}

		if let Some(identity) = &self.client_identity {
			let cert = (*identity.certificate).clone();
			let key = (*identity.key).clone();
			configured = configured.with_client_identity(cert, key);
		}

		configured
	}
}

/// Builder for creating a configured ConnectionPool
pub struct ConnectionPoolBuilder<P: Protocol, C: CryptoProvider = DefaultCryptoProvider> {
	config: PoolConfig,
	timeout: Option<Duration>,
	#[cfg(feature = "x509")]
	tls: PoolTlsConfig<C>,
	_phantom: core::marker::PhantomData<(P, C)>,
}

impl<P: Protocol, C: CryptoProvider> Default for ConnectionPoolBuilder<P, C> {
	fn default() -> Self {
		Self {
			config: PoolConfig::default(),
			timeout: None,
			#[cfg(feature = "x509")]
			tls: PoolTlsConfig::default(),
			_phantom: core::marker::PhantomData,
		}
	}
}

impl<P: Protocol, C: CryptoProvider> ConnectionPoolBuilder<P, C> {
	pub fn with_config(mut self, config: PoolConfig) -> Self {
		self.config = config;
		self
	}
}

#[cfg(feature = "std")]
impl<P: Protocol, C: CryptoProvider + Send + Sync + 'static> ConnectionBuilder<P> for ConnectionPoolBuilder<P, C> {
	type Output = ConnectionPool<P, C>;

	fn with_timeout(mut self, timeout: Duration) -> Self {
		self.timeout = Some(timeout);
		self
	}

	#[cfg(feature = "x509")]
	fn with_trust_store(mut self, store: Arc<dyn CertificateTrust>) -> Self {
		self.tls.set_trust_store(store);
		self
	}

	#[cfg(feature = "x509")]
	fn with_client_identity(
		mut self,
		cert: CertificateSpec,
		key: Arc<dyn SigningKeyProvider>,
	) -> TransportResult<Self> {
		let cert_converted = Certificate::try_from(cert)?;
		let key_converted: HandshakeKeyManager<C> = HandshakeKeyManager::new(key);

		self.tls.set_client_identity(cert_converted, key_converted);
		Ok(self)
	}

	fn build(self) -> Self::Output {
		ConnectionPool {
			pools: Arc::new(RwLock::new(HashMap::new())),
			config: self.config,
			timeout: self.timeout,
			total_connections: Arc::new(AtomicUsize::new(0)),
			#[cfg(feature = "x509")]
			tls: self.tls,
		}
	}
}

#[cfg(feature = "std")]
struct AvailableEntry<P: Protocol> {
	client: GenericClient<P>,
	last_used: Instant,
}

/// Per-destination connection pool
#[cfg(feature = "std")]
struct DestinationPool<P: Protocol> {
	/// Available connections ready for reuse
	available: VecDeque<AvailableEntry<P>>,
	/// Number of connections currently in use
	in_use: usize,
}

/// Connection pool for protocol P with global connection limit
///
/// # Invariants
/// - Total connections across all destinations <= `config.max_connections`
/// - Idle connections exceeding `PoolConfig::idle_timeout` are pruned lazily
/// - Lock poisoning never panics; callers receive `TransportFailure::Busy` instead
#[cfg(feature = "std")]
pub struct ConnectionPool<P: Protocol, C: CryptoProvider = DefaultCryptoProvider> {
	/// Per-destination sub-pools
	pools: Arc<RwLock<HashMap<P::Address, DestinationPool<P>>>>,
	/// Pool configuration
	config: PoolConfig,
	/// Shared timeout for all connections
	timeout: Option<Duration>,
	/// Total connections across all destinations
	total_connections: Arc<AtomicUsize>,
	/// Shared TLS assets reused across pooled connections
	#[cfg(feature = "x509")]
	tls: PoolTlsConfig<C>,
}

#[cfg(feature = "std")]
impl<P: Protocol + Send + Sync, C: CryptoProvider + Send + Sync + 'static> ConnectionPool<P, C>
where
	P::Address: Hash + Eq + Clone + Send + Sync,
	P::Transport: Send + Sync,
{
	/// Create a new connection pool builder
	pub fn builder() -> ConnectionPoolBuilder<P, C> {
		ConnectionPoolBuilder::default()
	}

	fn wrap_client(self: &Arc<Self>, client: GenericClient<P>, addr: P::Address) -> PooledClient<P, C>
	where
		P: PersistentConnection,
	{
		PooledClient { client: Some(client), pool: Arc::clone(self), addr }
	}

	fn write_pools(&self) -> TransportResult<RwLockWriteGuard<'_, HashMap<P::Address, DestinationPool<P>>>> {
		self.pools
			.write()
			.map_err(|_| TransportError::OperationFailed(TransportFailure::Busy))
	}

	#[cfg(not(feature = "x509"))]
	fn apply_timeout_to_builder<B>(&self, builder: B) -> B
	where
		B: ConnectionBuilder<P>,
	{
		if let Some(timeout) = self.timeout {
			builder.with_timeout(timeout)
		} else {
			builder
		}
	}

	fn try_take_ready_client(self: &Arc<Self>, addr: &P::Address) -> TransportResult<Option<GenericClient<P>>>
	where
		P: PersistentConnection,
	{
		let mut pools = self.write_pools()?;
		if let Some(dest_pool) = pools.get_mut(addr) {
			self.prune_idle_locked(dest_pool, Instant::now());
			while let Some(entry) = dest_pool.available.pop_front() {
				if <P as PersistentConnection>::is_connected(entry.client.transport()) {
					dest_pool.in_use += 1;
					return Ok(Some(entry.client));
				}
			}
		}
		Ok(None)
	}

	fn reserve_slot(self: &Arc<Self>, addr: &P::Address) -> TransportResult<SlotGuard<P, C>> {
		// Check global limit
		let current = self.total_connections.load(Ordering::Acquire);
		if current >= self.config.max_connections {
			return Err(TransportError::OperationFailed(TransportFailure::Busy));
		}

		// Atomically increment global counter
		self.total_connections.fetch_add(1, Ordering::AcqRel);

		let mut pools = self.write_pools()?;
		let dest_pool = pools
			.entry(addr.clone())
			.or_insert_with(|| DestinationPool { available: VecDeque::new(), in_use: 0 });

		self.prune_idle_locked(dest_pool, Instant::now());

		dest_pool.in_use += 1;

		Ok(SlotGuard::new(Arc::clone(self), addr.clone()))
	}

	fn prune_idle_locked(&self, dest_pool: &mut DestinationPool<P>, now: Instant) {
		if let Some(timeout) = self.config.idle_timeout {
			while let Some(entry) = dest_pool.available.front() {
				if now.duration_since(entry.last_used) >= timeout {
					dest_pool.available.pop_front();
				} else {
					break;
				}
			}
		}
	}

	#[cfg(not(feature = "x509"))]
	pub async fn connect(self: &Arc<Self>, addr: P::Address) -> TransportResult<PooledClient<P, C>>
	where
		P: PersistentConnection + Send + Sync,
		P::Transport: MessageEmitter + MessageCollector + PolicyConf + Send + Sync,
	{
		if let Some(client) = self.try_take_ready_client(&addr)? {
			return Ok(self.wrap_client(client, addr));
		}

		let mut reservation = self.reserve_slot(&addr)?;

		let builder = self.apply_timeout_to_builder(ClientBuilder::<P, C>::builder());
		let builder = ConnectionBuilder::build(builder);
		let client = builder.connect(addr.clone()).await?;

		reservation.disarm();

		Ok(self.wrap_client(client, addr))
	}

	#[cfg(feature = "x509")]
	pub async fn connect(self: &Arc<Self>, addr: P::Address) -> TransportResult<PooledClient<P, C>>
	where
		P: PersistentConnection + Send + Sync,
		P::Transport:
			MessageEmitter + MessageCollector + PolicyConf + X509ClientConfig<CryptoProvider = C> + Send + Sync,
	{
		if let Some(client) = self.try_take_ready_client(&addr)? {
			return Ok(self.wrap_client(client, addr));
		}

		let mut reservation = self.reserve_slot(&addr)?;
		let stream = P::connect(addr.clone()).await.map_err(|e| e.into())?;

		let mut transport = self.tls.apply::<P>(P::create_transport(stream));
		if let Some(timeout) = self.timeout {
			transport = transport.with_timeout(timeout);
		}

		let client = GenericClient::from_transport_with_addr(transport, addr.clone());

		reservation.disarm();

		Ok(self.wrap_client(client, addr))
	}

	pub fn try_acquire(self: &Arc<Self>, addr: &P::Address) -> TransportResult<Option<PooledClient<P, C>>>
	where
		P: PersistentConnection + Send + Sync,
		P::Transport: MessageEmitter + MessageCollector + PolicyConf + Send + Sync,
	{
		let maybe_client = self.try_take_ready_client(addr)?;
		Ok(maybe_client.map(|client| self.wrap_client(client, addr.clone())))
	}
}

// Separate impl with tighter bounds for non-x509 features
#[cfg(feature = "std")]
#[cfg(not(feature = "x509"))]
impl<P: Protocol + Send + Sync, C: CryptoProvider + Send + Sync + 'static> ConnectionPool<P, C>
where
	P::Address: Hash + Eq + Clone + Send + Sync,
	P::Transport: Send + Sync,
{
}

/// A pooled client connection that returns to the pool on drop
#[cfg(feature = "std")]
pub struct PooledClient<P: Protocol + PersistentConnection, C: CryptoProvider = DefaultCryptoProvider>
where
	P::Address: Hash + Eq + Send + Sync,
{
	client: Option<GenericClient<P>>,
	pool: Arc<ConnectionPool<P, C>>,
	addr: P::Address,
}

#[cfg(feature = "std")]
impl<P: Protocol + PersistentConnection, C: CryptoProvider> PooledClient<P, C>
where
	P::Address: Hash + Eq + Send + Sync,
{
	/// Returns a mutable reference to the underlying connection
	pub fn conn(&mut self) -> TransportResult<&mut GenericClient<P>> {
		self.client
			.as_mut()
			.ok_or(TransportError::OperationFailed(TransportFailure::Busy))
	}
}

#[cfg(feature = "std")]
impl<P: Protocol + PersistentConnection, C: CryptoProvider> Drop for PooledClient<P, C>
where
	P::Address: Hash + Eq + Send + Sync,
{
	fn drop(&mut self) {
		let client = match self.client.take() {
			Some(client) => client,
			None => return,
		};

		// Decrement global counter
		self.pool.total_connections.fetch_sub(1, Ordering::AcqRel);

		let is_healthy = <P as PersistentConnection>::is_connected(client.transport());
		let mut pools = match self.pool.pools.write() {
			Ok(p) => p,
			Err(_) => return,
		};

		if let Some(dest_pool) = pools.get_mut(&self.addr) {
			dest_pool.in_use = dest_pool.in_use.saturating_sub(1);
			if is_healthy {
				dest_pool
					.available
					.push_back(AvailableEntry { client, last_used: Instant::now() });
			}
		}
	}
}

#[cfg(feature = "std")]
struct SlotGuard<P: Protocol, C: CryptoProvider = DefaultCryptoProvider>
where
	P::Address: Hash + Eq + Clone + Send + Sync,
{
	pool: Arc<ConnectionPool<P, C>>,
	addr: P::Address,
	active: bool,
}

#[cfg(feature = "std")]
impl<P: Protocol, C: CryptoProvider> SlotGuard<P, C>
where
	P::Address: Hash + Eq + Clone + Send + Sync,
{
	fn new(pool: Arc<ConnectionPool<P, C>>, addr: P::Address) -> Self {
		Self { pool, addr, active: true }
	}

	fn disarm(&mut self) {
		self.active = false;
	}
}

#[cfg(feature = "std")]
impl<P: Protocol, C: CryptoProvider> Drop for SlotGuard<P, C>
where
	P::Address: Hash + Eq + Clone + Send + Sync,
{
	fn drop(&mut self) {
		if !self.active {
			return;
		}

		// Decrement global counter
		self.pool.total_connections.fetch_sub(1, Ordering::AcqRel);

		let pools = self.pool.pools.write();
		if let Ok(mut pools) = pools {
			if let Some(dest_pool) = pools.get_mut(&self.addr) {
				dest_pool.in_use = dest_pool.in_use.saturating_sub(1);
			}
		}
	}
}

#[cfg(all(test, feature = "std"))]
mod tests {
	use super::*;

	#[test]
	fn test_pool_config_default() {
		let config = PoolConfig::default();
		assert!(config.idle_timeout.is_none());
		assert_eq!(config.max_connections, 64);
	}

	#[test]
	fn test_pool_config_with_timeout() {
		let config = PoolConfig { idle_timeout: Some(Duration::from_secs(30)), max_connections: 64 };
		assert_eq!(config.idle_timeout, Some(Duration::from_secs(30)));
	}

	#[test]
	fn test_pool_config_with_max_connections() {
		let config = PoolConfig { idle_timeout: None, max_connections: 16 };
		assert_eq!(config.max_connections, 16);
	}
}