Skip to main content

alloy_node_bindings/
utils.rs

1//! Utility functions for the node bindings.
2
3use std::{
4    borrow::Cow,
5    future::Future,
6    net::{SocketAddr, TcpListener},
7    path::PathBuf,
8    process::Child,
9    time::{Duration, Instant},
10};
11use tempfile::TempDir;
12
13#[cfg(unix)]
14use libc;
15
16/// Helper for graceful process shutdown.
17pub(crate) struct GracefulShutdown;
18
19impl GracefulShutdown {
20    /// Attempts graceful shutdown with SIGTERM, then SIGKILL after timeout.
21    pub(crate) fn shutdown(child: &mut Child, timeout_secs: u64, process_name: &str) {
22        #[cfg(unix)]
23        {
24            unsafe {
25                libc::kill(child.id() as i32, libc::SIGTERM);
26            }
27
28            let timeout = Duration::from_secs(timeout_secs);
29            let start = Instant::now();
30
31            while start.elapsed() < timeout {
32                match child.try_wait() {
33                    Ok(Some(_)) => return,
34                    Ok(None) => std::thread::sleep(Duration::from_millis(100)),
35                    Err(_) => break,
36                }
37            }
38        }
39
40        child.kill().unwrap_or_else(|_| panic!("could not kill {}", process_name));
41    }
42}
43
44/// A bit of hack to find an unused TCP port.
45///
46/// Does not guarantee that the given port is unused after the function exists, just that it was
47/// unused before the function started (i.e., it does not reserve a port).
48pub(crate) fn unused_port() -> u16 {
49    let listener = TcpListener::bind("127.0.0.1:0")
50        .expect("Failed to create TCP listener to find unused port");
51
52    let local_addr =
53        listener.local_addr().expect("Failed to read TCP listener local_addr to find unused port");
54    local_addr.port()
55}
56
57/// Extracts the value for the given key from the line of text.
58///
59/// It supports keys that end with '=' or ': '.
60/// For keys end with '=', find value until ' ' is encountered or end of line
61/// For keys end with ':', find value until ',' is encountered or end of line
62pub(crate) fn extract_value<'a>(key: &str, line: &'a str) -> Option<&'a str> {
63    let mut key_equal = Cow::from(key);
64    let mut key_colon = Cow::from(key);
65
66    // Prepare both key variants
67    if !key_equal.ends_with('=') {
68        key_equal = format!("{key}=").into();
69    }
70    if !key_colon.ends_with(": ") {
71        key_colon = format!("{key}: ").into();
72    }
73
74    // Try to find the key with '='
75    if let Some(pos) = line.find(key_equal.as_ref()) {
76        let start = pos + key_equal.len();
77        let end = line[start..].find(' ').map(|i| start + i).unwrap_or(line.len());
78        return Some(line[start..end].trim());
79    }
80
81    // If not found, try to find the key with ': '
82    if let Some(pos) = line.find(key_colon.as_ref()) {
83        let start = pos + key_colon.len();
84        let end = line[start..].find(',').map(|i| start + i).unwrap_or(line.len()); // Assuming comma or end of line
85        return Some(line[start..end].trim());
86    }
87
88    // If neither variant matches, return None
89    None
90}
91
92/// Extracts the endpoint from the given line.
93pub(crate) fn extract_endpoint(key: &str, line: &str) -> Option<SocketAddr> {
94    extract_value(key, line)
95        .map(|val| val.trim_start_matches("Some(").trim_end_matches(')'))
96        .and_then(|val| val.parse().ok())
97}
98
99/// Runs the given closure with a temporary directory.
100pub fn run_with_tempdir_sync(prefix: &str, f: impl FnOnce(PathBuf)) {
101    let temp_dir = TempDir::with_prefix(prefix).unwrap();
102    let temp_dir_path = temp_dir.path().to_path_buf();
103    f(temp_dir_path);
104}
105
106/// Runs the given async closure with a temporary directory.
107pub async fn run_with_tempdir<F, Fut>(prefix: &str, f: F)
108where
109    F: FnOnce(PathBuf) -> Fut,
110    Fut: Future<Output = ()>,
111{
112    let temp_dir = TempDir::with_prefix(prefix).unwrap();
113    let temp_dir_path = temp_dir.path().to_path_buf();
114    f(temp_dir_path).await;
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120    use std::net::SocketAddr;
121
122    #[test]
123    fn test_extract_value_with_equals() {
124        let line = "key=value some other text";
125        assert_eq!(extract_value("key", line), Some("value"));
126    }
127
128    #[test]
129    fn test_extract_value_with_colon() {
130        let line = "key: value, more text here";
131        assert_eq!(extract_value("key", line), Some("value"));
132    }
133
134    #[test]
135    fn test_extract_value_not_found() {
136        let line = "unrelated text";
137        assert_eq!(extract_value("key", line), None);
138    }
139
140    #[test]
141    fn test_extract_value_equals_no_space() {
142        let line = "INFO key=";
143        assert_eq!(extract_value("key", line), Some(""))
144    }
145
146    #[test]
147    fn test_extract_value_colon_no_comma() {
148        let line = "INFO key: value";
149        assert_eq!(extract_value("key", line), Some("value"))
150    }
151
152    #[test]
153    fn test_extract_http_address() {
154        let line = "INFO [07-01|13:20:42.774] HTTP server started                      endpoint=127.0.0.1:8545 auth=false prefix= cors= vhosts=localhost";
155        assert_eq!(
156            extract_endpoint("endpoint=", line),
157            Some(SocketAddr::from(([127, 0, 0, 1], 8545)))
158        );
159    }
160
161    #[test]
162    fn test_extract_udp_address() {
163        let line = "Updated local ENR enr=Enr { id: Some(\"v4\"), seq: 2, NodeId: 0x04dad428038b4db230fc5298646e137564fc6861662f32bdbf220f31299bdde7, signature: \"416520d69bfd701d95f4b77778970a5c18fa86e4dd4dc0746e80779d986c68605f491c01ef39cd3739fdefc1e3558995ad2f5d325f9e1db795896799e8ee94a3\", IpV4 UDP Socket: Some(0.0.0.0:30303), IpV6 UDP Socket: None, IpV4 TCP Socket: Some(0.0.0.0:30303), IpV6 TCP Socket: None, Other Pairs: [(\"eth\", \"c984fc64ec0483118c30\"), (\"secp256k1\", \"a103aa181e8fd5df651716430f1d4b504b54d353b880256f56aa727beadd1b7a9766\")], .. }";
164        assert_eq!(
165            extract_endpoint("IpV4 TCP Socket: ", line),
166            Some(SocketAddr::from(([0, 0, 0, 0], 30303)))
167        );
168    }
169
170    #[test]
171    fn test_unused_port() {
172        let port = unused_port();
173        assert!(port > 0);
174    }
175
176    #[test]
177    fn test_run_with_tempdir_sync() {
178        run_with_tempdir_sync("test_prefix", |path| {
179            assert!(path.exists(), "Temporary directory should exist");
180            assert!(path.is_dir(), "Temporary directory should be a directory");
181        });
182    }
183
184    #[tokio::test]
185    async fn test_run_with_tempdir_async() {
186        run_with_tempdir("test_prefix", |path| async move {
187            assert!(path.exists(), "Temporary directory should exist");
188            assert!(path.is_dir(), "Temporary directory should be a directory");
189        })
190        .await;
191    }
192}