Skip to main content

rusteron_media_driver/
testing.rs

1//! Test/example support: an embedded media driver with RAII teardown.
2//!
3//! The driver stops and joins on `Drop`, so teardown order lives in one place.
4
5use crate::{Aeron, AeronCError, AeronDriver, AeronDriverContext, IntoCString};
6use std::sync::Arc;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::thread::JoinHandle;
9
10/// An embedded media driver running on a background thread, with a unique directory,
11/// stopped and joined automatically on `Drop`.
12///
13/// ```no_run
14/// # use rusteron_media_driver::testing::EmbeddedDriver;
15/// let driver = EmbeddedDriver::launch().unwrap();
16/// // connect clients against driver.dir() ...
17/// // driver stops + joins when it goes out of scope
18/// ```
19pub struct EmbeddedDriver {
20    dir: String,
21    context: AeronDriverContext,
22    stop: Arc<AtomicBool>,
23    handle: Option<JoinHandle<Result<(), AeronCError>>>,
24}
25
26impl EmbeddedDriver {
27    /// Launch an embedded driver in a unique directory (deleted on start and shutdown).
28    pub fn launch() -> Result<Self, AeronCError> {
29        Self::launch_with(|_| Ok(()))
30    }
31
32    /// Launch with extra [`AeronDriverContext`] configuration (timeouts, idle strategies…)
33    /// applied before the driver starts.
34    pub fn launch_with(
35        configure: impl FnOnce(&AeronDriverContext) -> Result<(), AeronCError>,
36    ) -> Result<Self, AeronCError> {
37        let context = AeronDriverContext::new()?;
38        context.set_dir_delete_on_shutdown(true)?;
39        context.set_dir_delete_on_start(true)?;
40        context.set_dir(&format!("{}{}", context.get_dir(), Aeron::nano_clock()).into_c_string())?;
41        configure(&context)?;
42        let dir = context.get_dir().to_string();
43        let (stop, handle) = AeronDriver::launch_embedded(context.clone(), false);
44        Ok(Self {
45            dir,
46            context,
47            stop,
48            handle: Some(handle),
49        })
50    }
51
52    /// The aeron directory clients should connect to.
53    #[inline]
54    pub fn dir(&self) -> &str {
55        &self.dir
56    }
57
58    /// The driver's context, e.g. for reading configured values.
59    #[inline]
60    pub fn context(&self) -> &AeronDriverContext {
61        &self.context
62    }
63
64    /// Stop the driver now instead of waiting for `Drop`.
65    pub fn stop(mut self) {
66        self.stop_and_join();
67    }
68
69    fn stop_and_join(&mut self) {
70        self.stop.store(true, Ordering::SeqCst);
71        if let Some(handle) = self.handle.take() {
72            let _ = handle.join();
73        }
74    }
75}
76
77impl Drop for EmbeddedDriver {
78    fn drop(&mut self) {
79        self.stop_and_join();
80    }
81}
82
83/// First free UDP port at or above `start` (binds a probe socket to check).
84pub fn find_unused_udp_port(start: u16) -> Option<u16> {
85    (start..65535).find(|p| std::net::UdpSocket::bind(("127.0.0.1", *p)).is_ok())
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    #[test]
93    fn embedded_driver_launches_and_stops_on_drop() {
94        let driver = EmbeddedDriver::launch().unwrap();
95        assert!(!driver.dir().is_empty());
96        let dir = driver.dir().to_string();
97        drop(driver); // stops + joins; dir deleted on shutdown
98        assert!(!std::path::Path::new(&dir).join("cnc.dat").exists());
99    }
100
101    #[test]
102    fn find_unused_udp_port_returns_bindable_port() {
103        let port = find_unused_udp_port(23000).unwrap();
104        assert!(std::net::UdpSocket::bind(("127.0.0.1", port)).is_ok());
105    }
106}