reinhardt-db 0.1.0

Django-style database layer for Reinhardt framework
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! Connection pool implementation

use super::config::PoolConfig;
use super::errors::{PoolError, PoolResult};
use super::events::{PoolEvent, PoolEventListener};
use sqlx::{Database, MySql, Pool, Postgres, Sqlite};
use std::mem::ManuallyDrop;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::RwLock;

/// Mask the password in a database URL for safe display.
///
/// Handles standard URL formats like `scheme://user:password@host/db`
/// and replaces the password portion with `***`.
/// Correctly handles passwords containing `@` by using the last `@` as
/// the user-info delimiter.
pub(crate) fn mask_url_password(url: &str) -> String {
	// Try to parse as a standard URL with scheme://user:pass@host format
	if let Some(scheme_end) = url.find("://") {
		let after_scheme = &url[scheme_end + 3..];

		// Use the last @ as the user-info delimiter, since passwords may contain @
		if let Some(at_pos) = after_scheme.rfind('@') {
			let user_info = &after_scheme[..at_pos];

			// Find the first colon separating user from password
			if let Some(colon_pos) = user_info.find(':') {
				let scheme_and_user = &url[..scheme_end + 3 + colon_pos + 1];
				let rest = &url[scheme_end + 3 + at_pos..];
				return format!("{}***{}", scheme_and_user, rest);
			}
		}
	}

	// No password found, return as-is
	url.to_string()
}

/// A database connection pool
pub struct ConnectionPool<DB: Database> {
	pool: Pool<DB>,
	config: PoolConfig,
	url: String,
	listeners: Arc<RwLock<Vec<Arc<dyn PoolEventListener>>>>,
	first_connect_fired: Arc<AtomicBool>,
}

impl ConnectionPool<Postgres> {
	/// Create a new PostgreSQL connection pool
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::pool::{ConnectionPool, PoolConfig};
	///
	/// # async fn example() {
	/// let config = PoolConfig::default();
	/// // For doctest purposes, using SQLite in-memory instead of PostgreSQL
	/// let pool = ConnectionPool::new_sqlite("sqlite::memory:", config).await.unwrap();
	/// assert!(pool.url().contains("memory"));
	/// assert_eq!(pool.config().max_connections, 10);
	/// # }
	/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
	/// ```
	pub async fn new_postgres(url: &str, config: PoolConfig) -> PoolResult<Self> {
		config.validate().map_err(PoolError::Config)?;

		let pool = sqlx::postgres::PgPoolOptions::new()
			.min_connections(config.min_connections)
			.max_connections(config.max_connections)
			.acquire_timeout(config.acquire_timeout)
			.idle_timeout(config.idle_timeout)
			.max_lifetime(config.max_lifetime)
			.test_before_acquire(config.test_before_acquire)
			.connect(url)
			.await?;

		Ok(Self {
			pool,
			config,
			url: url.to_string(),
			listeners: Arc::new(RwLock::new(Vec::new())),
			first_connect_fired: Arc::new(AtomicBool::new(false)),
		})
	}
}

impl ConnectionPool<MySql> {
	/// Create a new MySQL connection pool
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::pool::{ConnectionPool, PoolConfig};
	///
	/// # async fn example() {
	/// let config = PoolConfig::default();
	/// // For doctest purposes, using SQLite in-memory instead of MySQL
	/// let pool = ConnectionPool::new_sqlite("sqlite::memory:", config).await.unwrap();
	/// assert!(pool.url().contains("memory"));
	/// assert_eq!(pool.config().max_connections, 10);
	/// # }
	/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
	/// ```
	pub async fn new_mysql(url: &str, config: PoolConfig) -> PoolResult<Self> {
		config.validate().map_err(PoolError::Config)?;

		let pool = sqlx::mysql::MySqlPoolOptions::new()
			.min_connections(config.min_connections)
			.max_connections(config.max_connections)
			.acquire_timeout(config.acquire_timeout)
			.idle_timeout(config.idle_timeout)
			.max_lifetime(config.max_lifetime)
			.test_before_acquire(config.test_before_acquire)
			.connect(url)
			.await?;

		Ok(Self {
			pool,
			config,
			url: url.to_string(),
			listeners: Arc::new(RwLock::new(Vec::new())),
			first_connect_fired: Arc::new(AtomicBool::new(false)),
		})
	}
}

impl ConnectionPool<Sqlite> {
	/// Create a new SQLite connection pool
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::pool::{ConnectionPool, PoolConfig};
	///
	/// # async fn example() {
	/// let config = PoolConfig::default();
	/// // Using in-memory SQLite for doctest
	/// let pool = ConnectionPool::new_sqlite("sqlite::memory:", config).await.unwrap();
	/// assert!(pool.url().contains("memory"));
	/// assert!(pool.config().max_connections > 0);
	/// # }
	/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
	/// ```
	pub async fn new_sqlite(url: &str, config: PoolConfig) -> PoolResult<Self> {
		config.validate().map_err(PoolError::Config)?;

		let pool = sqlx::sqlite::SqlitePoolOptions::new()
			.min_connections(config.min_connections)
			.max_connections(config.max_connections)
			.acquire_timeout(config.acquire_timeout)
			.idle_timeout(config.idle_timeout)
			.max_lifetime(config.max_lifetime)
			.test_before_acquire(config.test_before_acquire)
			.connect(url)
			.await?;

		Ok(Self {
			pool,
			config,
			url: url.to_string(),
			listeners: Arc::new(RwLock::new(Vec::new())),
			first_connect_fired: Arc::new(AtomicBool::new(false)),
		})
	}
}

impl<DB> ConnectionPool<DB>
where
	DB: sqlx::Database,
{
	/// Add an event listener
	///
	pub async fn add_listener(&self, listener: Arc<dyn PoolEventListener>) {
		let mut listeners = self.listeners.write().await;
		listeners.push(listener);
	}

	/// Emit an event to all listeners
	pub(crate) async fn emit_event(&self, event: PoolEvent) {
		let listeners = self.listeners.read().await;
		for listener in listeners.iter() {
			listener.on_event(event.clone()).await;
		}
	}
	/// Acquire a connection from the pool with event emission
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_db::pool::{ConnectionPool, PoolConfig};
	///
	/// # async fn example() {
	/// let config = PoolConfig::default();
	/// let pool = ConnectionPool::new_postgres("postgresql://user:pass@localhost/test", config)
	///     .await
	///     .unwrap();
	///
	/// // Acquire a connection
	/// let conn = pool.acquire().await;
	/// assert!(conn.is_ok());
	/// # }
	/// ```
	pub async fn acquire(&self) -> PoolResult<PooledConnection<DB>> {
		// Check if this is the first connection
		let is_first = !self.first_connect_fired.swap(true, Ordering::SeqCst);

		let conn = self.pool.acquire().await?;
		let connection_id = uuid::Uuid::now_v7().to_string();

		if is_first {
			// Emit first_connect event (using ConnectionCreated as proxy)
			self.emit_event(PoolEvent::connection_created(connection_id.clone()))
				.await;
		}

		// Emit checkout event
		self.emit_event(PoolEvent::connection_acquired(connection_id.clone()))
			.await;

		Ok(PooledConnection {
			conn: ManuallyDrop::new(conn),
			pool_ref: self.clone_arc(),
			connection_id,
		})
	}

	/// Clone as Arc for sharing with PooledConnection
	fn clone_arc(&self) -> Arc<Self> {
		Arc::new(Self {
			pool: self.pool.clone(),
			config: self.config.clone(),
			url: self.url.clone(),
			listeners: self.listeners.clone(),
			first_connect_fired: self.first_connect_fired.clone(),
		})
	}
	/// Get the underlying pool
	///
	pub fn inner(&self) -> &Pool<DB> {
		&self.pool
	}
	/// Get pool configuration
	///
	pub fn config(&self) -> &PoolConfig {
		&self.config
	}
	/// Close the pool
	///
	/// Attempts to gracefully close the pool with a 5-second timeout.
	/// If active connections are not returned within this time, the pool
	/// will be forcefully closed.
	pub async fn close(&self) {
		use tokio::time::{Duration, timeout};

		// Try to close gracefully with a timeout
		let close_future = self.pool.close();
		if timeout(Duration::from_secs(5), close_future).await.is_err() {
			// Timeout occurred - pool had active connections
			// The pool will be forcefully closed when dropped
		}
	}
	/// Get the database URL with password masked for safe display
	///
	/// Returns the database URL with any password replaced by `***`
	/// to prevent credential exposure in logs and debug output.
	/// Use `url_raw()` when the actual password is needed for reconnection.
	pub fn url(&self) -> String {
		mask_url_password(&self.url)
	}

	/// Get the raw database URL including credentials
	///
	/// This method returns the unmasked URL containing the actual password.
	/// Use with caution - prefer `url()` for logging and display purposes.
	// Allow dead_code: preserved for internal use by reconnection logic (e.g., `recreate()`)
	#[allow(dead_code)]
	pub(crate) fn url_raw(&self) -> &str {
		&self.url
	}
}

// Database-specific recreate implementations
impl ConnectionPool<Postgres> {
	/// Recreate the pool with the same configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::pool::{ConnectionPool, PoolConfig};
	///
	/// # async fn example() {
	/// let config = PoolConfig::default();
	/// // For doctest purposes, using SQLite in-memory instead of PostgreSQL
	/// let mut pool = ConnectionPool::new_sqlite("sqlite::memory:", config)
	///     .await
	///     .unwrap();
	///
	/// // Recreate the pool
	/// pool.recreate().await.unwrap();
	/// assert_eq!(pool.config().max_connections, 10);
	/// # }
	/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
	/// ```
	pub async fn recreate(&mut self) -> PoolResult<()> {
		// Close existing pool
		self.pool.close().await;

		// Create new pool with same configuration
		let new_pool = sqlx::postgres::PgPoolOptions::new()
			.min_connections(self.config.min_connections)
			.max_connections(self.config.max_connections)
			.acquire_timeout(self.config.acquire_timeout)
			.idle_timeout(self.config.idle_timeout)
			.max_lifetime(self.config.max_lifetime)
			.test_before_acquire(self.config.test_before_acquire)
			.connect(&self.url)
			.await?;

		self.pool = new_pool;
		self.first_connect_fired.store(false, Ordering::SeqCst);

		Ok(())
	}
}

impl ConnectionPool<MySql> {
	/// Recreate the pool with the same configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::pool::{ConnectionPool, PoolConfig};
	///
	/// # async fn example() {
	/// let config = PoolConfig::default();
	/// // For doctest purposes, using SQLite in-memory instead of MySQL
	/// let mut pool = ConnectionPool::new_sqlite("sqlite::memory:", config)
	///     .await
	///     .unwrap();
	///
	/// // Recreate the pool
	/// pool.recreate().await.unwrap();
	/// assert_eq!(pool.config().max_connections, 10);
	/// # }
	/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
	/// ```
	pub async fn recreate(&mut self) -> PoolResult<()> {
		// Close existing pool
		self.pool.close().await;

		// Create new pool with same configuration
		let new_pool = sqlx::mysql::MySqlPoolOptions::new()
			.min_connections(self.config.min_connections)
			.max_connections(self.config.max_connections)
			.acquire_timeout(self.config.acquire_timeout)
			.idle_timeout(self.config.idle_timeout)
			.max_lifetime(self.config.max_lifetime)
			.test_before_acquire(self.config.test_before_acquire)
			.connect(&self.url)
			.await?;

		self.pool = new_pool;
		self.first_connect_fired.store(false, Ordering::SeqCst);

		Ok(())
	}
}

impl ConnectionPool<Sqlite> {
	/// Recreate the pool with the same configuration
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_db::pool::{ConnectionPool, PoolConfig};
	///
	/// # async fn example() {
	/// let config = PoolConfig::default();
	/// let mut pool = ConnectionPool::new_sqlite("sqlite::memory:", config)
	///     .await
	///     .unwrap();
	///
	/// // Recreate the pool
	/// pool.recreate().await.unwrap();
	/// assert!(pool.url().contains("memory"));
	/// # }
	/// # tokio::runtime::Runtime::new().unwrap().block_on(example());
	/// ```
	pub async fn recreate(&mut self) -> PoolResult<()> {
		// Close existing pool
		self.pool.close().await;

		// Create new pool with same configuration
		let new_pool = sqlx::sqlite::SqlitePoolOptions::new()
			.min_connections(self.config.min_connections)
			.max_connections(self.config.max_connections)
			.acquire_timeout(self.config.acquire_timeout)
			.idle_timeout(self.config.idle_timeout)
			.max_lifetime(self.config.max_lifetime)
			.test_before_acquire(self.config.test_before_acquire)
			.connect(&self.url)
			.await?;

		self.pool = new_pool;
		self.first_connect_fired.store(false, Ordering::SeqCst);

		Ok(())
	}
}

/// A pooled connection wrapper with event emission
pub struct PooledConnection<DB: sqlx::Database> {
	// Wrapped in ManuallyDrop so we can take ownership in Drop.
	// When no tokio runtime is available, we detach the connection
	// to avoid sqlx's PoolConnection::Drop calling rt::spawn().
	conn: ManuallyDrop<sqlx::pool::PoolConnection<DB>>,
	pool_ref: Arc<ConnectionPool<DB>>,
	connection_id: String,
}

impl<DB: sqlx::Database> PooledConnection<DB> {
	/// Documentation for `inner`
	///
	pub fn inner(&mut self) -> &mut sqlx::pool::PoolConnection<DB> {
		&mut self.conn
	}
	/// Get the unique identifier for this connection
	///
	/// # Examples
	///
	/// ```no_run
	/// use reinhardt_db::pool::{ConnectionPool, PoolConfig};
	///
	/// # async fn example() {
	/// let config = PoolConfig::default();
	/// let pool = ConnectionPool::new_postgres("postgresql://user:pass@localhost/test", config)
	///     .await
	///     .unwrap();
	///
	/// let mut conn = pool.acquire().await.unwrap();
	/// let id = conn.connection_id();
	/// assert!(!id.is_empty());
	/// # }
	/// ```
	pub fn connection_id(&self) -> &str {
		&self.connection_id
	}
	/// Invalidate this connection (hard invalidation - connection is unusable)
	///
	pub async fn invalidate(self, reason: String) {
		self.pool_ref
			.emit_event(PoolEvent::connection_invalidated(
				self.connection_id.clone(),
				reason,
			))
			.await;
		// Connection will be dropped and not returned to pool
	}
	/// Soft invalidate this connection (can complete current operation)
	///
	pub async fn soft_invalidate(&mut self) {
		self.pool_ref
			.emit_event(PoolEvent::connection_soft_invalidated(
				self.connection_id.clone(),
			))
			.await;
	}
	/// Reset this connection
	///
	pub async fn reset(&mut self) {
		self.pool_ref
			.emit_event(PoolEvent::connection_reset(self.connection_id.clone()))
			.await;
	}
}

impl<DB: sqlx::Database> Drop for PooledConnection<DB> {
	fn drop(&mut self) {
		// SAFETY: ManuallyDrop::take is called exactly once (in drop).
		let conn = unsafe { ManuallyDrop::take(&mut self.conn) };

		match tokio::runtime::Handle::try_current() {
			Ok(handle) => {
				// Runtime available: drop the connection normally (returns to pool)
				// and emit the connection-returned event.
				drop(conn);

				let pool_ref = self.pool_ref.clone();
				let connection_id = self.connection_id.clone();

				handle.spawn(async move {
					pool_ref
						.emit_event(PoolEvent::connection_returned(connection_id))
						.await;
				});
			}
			Err(_) => {
				// No runtime available: prevent sqlx's PoolConnection::Drop
				// from running, as it calls crate::rt::spawn() which panics
				// without a tokio runtime. The connection is intentionally
				// leaked to avoid the panic.
				std::mem::forget(conn);
			}
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;

	#[rstest]
	#[case(
		"postgresql://user:secret@localhost:5432/mydb",
		"postgresql://user:***@localhost:5432/mydb"
	)]
	#[case(
		"mysql://admin:p@ssw0rd@db.example.com/app",
		"mysql://admin:***@db.example.com/app"
	)]
	#[case(
		"postgres://user:pass@host:5432/db?sslmode=require",
		"postgres://user:***@host:5432/db?sslmode=require"
	)]
	fn test_mask_url_password_with_credentials(#[case] input: &str, #[case] expected: &str) {
		// Arrange
		// (input provided by case parameters)

		// Act
		let masked = mask_url_password(input);

		// Assert
		assert_eq!(masked, expected);
	}

	#[rstest]
	#[case("sqlite::memory:")]
	#[case("sqlite:///path/to/db.sqlite")]
	#[case("postgresql://user@localhost:5432/mydb")]
	fn test_mask_url_password_without_password(#[case] input: &str) {
		// Arrange
		// (input provided by case parameter)

		// Act
		let masked = mask_url_password(input);

		// Assert
		assert_eq!(masked, input, "URL without password should be unchanged");
	}

	#[rstest]
	fn test_mask_url_password_empty_password() {
		// Arrange
		let url = "postgresql://user:@localhost:5432/mydb";

		// Act
		let masked = mask_url_password(url);

		// Assert
		assert_eq!(masked, "postgresql://user:***@localhost:5432/mydb");
	}

	#[rstest]
	fn test_mask_url_password_special_chars_in_password() {
		// Arrange
		let url = "postgresql://user:p%40ss%3Aw0rd@localhost:5432/mydb";

		// Act
		let masked = mask_url_password(url);

		// Assert
		assert_eq!(masked, "postgresql://user:***@localhost:5432/mydb");
		assert!(
			!masked.contains("p%40ss"),
			"Password should be fully masked"
		);
	}

	#[rstest]
	fn test_mask_url_password_preserves_non_url() {
		// Arrange
		let non_url = "not-a-url-just-a-string";

		// Act
		let masked = mask_url_password(non_url);

		// Assert
		assert_eq!(
			masked, non_url,
			"Non-URL strings should pass through unchanged"
		);
	}

	#[rstest]
	fn test_handle_try_current_returns_err_outside_runtime() {
		// Arrange & Act & Assert
		// Run on a fresh thread to avoid inheriting runtime context
		// from the test runner's worker thread.
		let handle = std::thread::spawn(|| {
			let result = tokio::runtime::Handle::try_current();
			assert!(
				result.is_err(),
				"Handle::try_current() should return Err outside of a tokio runtime"
			);
		});
		handle.join().expect("thread should not panic");
	}

	#[rstest]
	fn test_drop_pooled_connection_outside_runtime_does_not_panic() {
		// Arrange
		// Create a Tokio runtime and acquire a pooled connection inside it.
		let rt = tokio::runtime::Runtime::new().expect("failed to create Tokio runtime");

		let (pool, conn) = rt.block_on(async {
			let config = PoolConfig::default();
			let pool = ConnectionPool::new_sqlite("sqlite::memory:", config)
				.await
				.expect("failed to create ConnectionPool");

			let conn = pool.acquire().await.expect("failed to acquire connection");

			(pool, conn)
		});

		// Drop the runtime so there is no active Tokio runtime.
		drop(rt);

		// Act & Assert
		// Dropping the connection outside any runtime should not panic.
		drop(conn);

		// Also drop the pool to ensure cleanup does not panic outside a runtime.
		drop(pool);
	}
}