Skip to main content

moonproof_node_client/
config.rs

1//! Configuration for the Midnight node client.
2//!
3//! Mirrors the TS `Config` from `PolkadotNodeClient.ts`: a node URL plus
4//! reconnection timing. Defaults match the TS reference so local-dev behavior
5//! stays aligned across runtimes.
6
7use std::time::Duration;
8use url::Url;
9
10/// Configuration for constructing a [`crate::NodeClient`].
11///
12/// The only required field is the node URL; everything else has sensible
13/// defaults via [`Config::new`].
14#[derive(Debug, Clone)]
15pub struct Config {
16    /// Node WebSocket URL, e.g. `ws://127.0.0.1:9944`. Must use the `ws://`
17    /// or `wss://` scheme — plain HTTP does not support subscriptions.
18    pub node_url: Url,
19
20    /// Total time the client will keep retrying to reconnect before giving
21    /// up. TS default is `Duration.infinity`; Rust default is a very large
22    /// but finite value (~293 years) so tests can enforce a ceiling.
23    pub reconnection_timeout: Duration,
24
25    /// Delay between consecutive reconnection attempts. TS default is 1s.
26    pub reconnection_delay: Duration,
27}
28
29impl Config {
30    /// Build a config from just a node URL, using the default reconnection
31    /// schedule (matches the TS `DEFAULT_CONFIG`: 1s delay, unbounded timeout).
32    #[must_use]
33    pub fn new(node_url: Url) -> Self {
34        Self {
35            node_url,
36            reconnection_timeout: Duration::MAX,
37            reconnection_delay: Duration::from_secs(1),
38        }
39    }
40
41    /// Override the reconnection timeout.
42    #[must_use]
43    pub fn with_reconnection_timeout(mut self, timeout: Duration) -> Self {
44        self.reconnection_timeout = timeout;
45        self
46    }
47
48    /// Override the reconnection delay.
49    #[must_use]
50    pub fn with_reconnection_delay(mut self, delay: Duration) -> Self {
51        self.reconnection_delay = delay;
52        self
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn new_populates_url_and_defaults_match_ts_reference() {
62        let url = Url::parse("ws://127.0.0.1:9944").unwrap();
63        let cfg = Config::new(url.clone());
64        assert_eq!(cfg.node_url, url);
65        assert_eq!(cfg.reconnection_delay, Duration::from_secs(1));
66        // TS uses `Duration.infinity`; we use Duration::MAX as the closest finite analog.
67        assert_eq!(cfg.reconnection_timeout, Duration::MAX);
68    }
69
70    #[test]
71    fn builder_overrides_apply_in_isolation() {
72        let url = Url::parse("wss://node.example:443").unwrap();
73        let cfg = Config::new(url)
74            .with_reconnection_delay(Duration::from_millis(250))
75            .with_reconnection_timeout(Duration::from_secs(30));
76        assert_eq!(cfg.reconnection_delay, Duration::from_millis(250));
77        assert_eq!(cfg.reconnection_timeout, Duration::from_secs(30));
78    }
79}