Skip to main content

finlight/
config.rs

1use std::fmt;
2use std::sync::Arc;
3use std::time::Duration;
4
5use crate::error::{Error, Result};
6use crate::ws::WsConnector;
7
8/// What the SDK does on a 429 `burst`.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10#[non_exhaustive]
11pub enum RetryOnBurst {
12    /// Wait exactly `Retry-After` (`burst_wait` when the header is missing), then retry once.
13    /// This retry does not count against `max_retries`.
14    #[default]
15    Once,
16    /// Return the error at once.
17    Off,
18}
19
20/// Configuration of a [`Client`](crate::Client). Build it with [`Config::builder`].
21///
22/// Durations are `std::time::Duration`. Every value can be overridden.
23#[derive(Clone)]
24#[non_exhaustive]
25pub struct Config {
26    api_key: String,
27    /// REST base URL. Default `https://api.finlight.me`.
28    pub base_url: String,
29    /// WebSocket URL. Default `wss://wss.finlight.me`; the raw stream uses `<wss_url>/raw`.
30    pub wss_url: String,
31    /// Timeout of one REST attempt. Default 30 s. Ignored with your own `http_client`.
32    pub timeout: Duration,
33    /// Upper bound of one REST call, retries and burst wait included. Default none.
34    pub total_timeout: Option<Duration>,
35    /// Retries after the first attempt for 5xx, network errors and attempt timeouts. Default 3.
36    pub max_retries: u32,
37    /// First backoff delay. Default 0.5 s.
38    pub retry_base_delay: Duration,
39    /// Largest backoff delay. Default 8 s.
40    pub retry_max_delay: Duration,
41    /// Behaviour on a 429 `burst`. Default [`RetryOnBurst::Once`].
42    pub retry_on_burst: RetryOnBurst,
43    /// Wait on a 429 `burst` without `Retry-After`. Default 10 s.
44    pub burst_wait: Duration,
45    /// Page limit of `search_all`. Default 10.
46    pub max_pages: u32,
47    /// Largest REST response body read. Default 32 MiB.
48    pub max_response_bytes: usize,
49    /// Interval of the application ping on streams. Default 25 s.
50    pub ping_interval: Duration,
51    /// A stream connection without a pong for this long is replaced. Default 60 s.
52    pub watchdog_timeout: Duration,
53    /// A stream connection is renewed after this long (the gateway ends it after 2 h). Default 115 min.
54    pub rotation_interval: Duration,
55    /// First reconnect delay of a stream. Default 1 s.
56    pub reconnect_base_delay: Duration,
57    /// Largest reconnect delay. Default 30 s.
58    pub reconnect_max_delay: Duration,
59    /// Wait after a refused dial because of the connection limit. Default 60 s.
60    pub long_backoff: Duration,
61    /// When the WebSocket quota is used up, keep the stream and redial every
62    /// `quota_reconnect_interval`. `false` ends the stream with the error. Default `true`.
63    pub quota_reconnect: bool,
64    /// Interval of quota redials. Default 1 h.
65    pub quota_reconnect_interval: Duration,
66    /// After this many `SEARCH_FAILED` in a row, the error goes to `on_error`. Default 5.
67    pub search_failed_threshold: u32,
68    /// Entries of the duplicate filter of each stream. Default 1000.
69    pub dedupe_cache_size: usize,
70    /// Largest incoming stream message. Default 32 MiB.
71    pub max_message_bytes: usize,
72    /// Timeout of the WebSocket dial and handshake. Default 30 s.
73    pub connect_timeout: Duration,
74    /// Your own `reqwest::Client` for REST. Its own timeouts apply; the SDK never closes it.
75    pub http_client: Option<reqwest::Client>,
76    /// Your own transport for WebSocket dials (e.g. through a proxy).
77    pub ws_connector: Option<Arc<dyn WsConnector>>,
78}
79
80impl Config {
81    /// A configuration with the defaults and this API key.
82    pub fn new(api_key: impl Into<String>) -> Self {
83        Config {
84            api_key: api_key.into(),
85            base_url: "https://api.finlight.me".to_owned(),
86            wss_url: "wss://wss.finlight.me".to_owned(),
87            timeout: Duration::from_secs(30),
88            total_timeout: None,
89            max_retries: 3,
90            retry_base_delay: Duration::from_millis(500),
91            retry_max_delay: Duration::from_secs(8),
92            retry_on_burst: RetryOnBurst::Once,
93            burst_wait: Duration::from_secs(10),
94            max_pages: 10,
95            max_response_bytes: 32 * 1024 * 1024,
96            ping_interval: Duration::from_secs(25),
97            watchdog_timeout: Duration::from_secs(60),
98            rotation_interval: Duration::from_secs(115 * 60),
99            reconnect_base_delay: Duration::from_secs(1),
100            reconnect_max_delay: Duration::from_secs(30),
101            long_backoff: Duration::from_secs(60),
102            quota_reconnect: true,
103            quota_reconnect_interval: Duration::from_secs(3600),
104            search_failed_threshold: 5,
105            dedupe_cache_size: 1000,
106            max_message_bytes: 32 * 1024 * 1024,
107            connect_timeout: Duration::from_secs(30),
108            http_client: None,
109            ws_connector: None,
110        }
111    }
112
113    /// A builder with the defaults and this API key.
114    pub fn builder(api_key: impl Into<String>) -> ConfigBuilder {
115        ConfigBuilder(Config::new(api_key))
116    }
117
118    pub(crate) fn api_key(&self) -> &str {
119        &self.api_key
120    }
121
122    pub(crate) fn validate(&self) -> Result<()> {
123        if self.api_key.trim().is_empty() {
124            return Err(Error::validation(
125                "api_key must not be empty",
126                Some("api_key"),
127            ));
128        }
129        if self.api_key.chars().any(|c| !c.is_ascii_graphic()) {
130            return Err(Error::validation(
131                "api_key may only contain printable ASCII characters",
132                Some("api_key"),
133            ));
134        }
135        for (name, url, schemes) in [
136            ("base_url", &self.base_url, &["http://", "https://"]),
137            ("wss_url", &self.wss_url, &["ws://", "wss://"]),
138        ] {
139            if !schemes.iter().any(|s| url.starts_with(s)) || reqwest::Url::parse(url).is_err() {
140                return Err(Error::validation(
141                    format!("{name} must be an absolute {} URL", schemes.join(" or ")),
142                    Some(name),
143                ));
144            }
145        }
146        if self.max_pages == 0 {
147            return Err(Error::validation(
148                "max_pages must be at least 1",
149                Some("max_pages"),
150            ));
151        }
152        if self.max_message_bytes < 16 * 1024 * 1024 {
153            return Err(Error::validation(
154                "max_message_bytes must be at least 16 MiB (the initial push has no size limit)",
155                Some("max_message_bytes"),
156            ));
157        }
158        for (name, d) in [
159            ("ping_interval", self.ping_interval),
160            ("watchdog_timeout", self.watchdog_timeout),
161            ("rotation_interval", self.rotation_interval),
162            ("quota_reconnect_interval", self.quota_reconnect_interval),
163            ("connect_timeout", self.connect_timeout),
164        ] {
165            if d.is_zero() {
166                return Err(Error::validation(
167                    format!("{name} must be greater than zero"),
168                    Some(name),
169                ));
170            }
171        }
172        Ok(())
173    }
174
175    /// `base_url` without a trailing slash.
176    pub(crate) fn rest_base(&self) -> &str {
177        self.base_url.trim_end_matches('/')
178    }
179
180    /// The enriched or raw stream URL.
181    pub(crate) fn stream_url(&self, raw: bool) -> String {
182        let base = self.wss_url.trim_end_matches('/');
183        if raw {
184            format!("{base}/raw")
185        } else {
186            format!("{base}/")
187        }
188    }
189}
190
191impl fmt::Debug for Config {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        // The API key is never printed.
194        f.debug_struct("Config")
195            .field("api_key", &"[redacted]")
196            .field("base_url", &self.base_url)
197            .field("wss_url", &self.wss_url)
198            .field("timeout", &self.timeout)
199            .field("total_timeout", &self.total_timeout)
200            .field("max_retries", &self.max_retries)
201            .field("retry_base_delay", &self.retry_base_delay)
202            .field("retry_max_delay", &self.retry_max_delay)
203            .field("retry_on_burst", &self.retry_on_burst)
204            .field("burst_wait", &self.burst_wait)
205            .field("max_pages", &self.max_pages)
206            .field("max_response_bytes", &self.max_response_bytes)
207            .field("ping_interval", &self.ping_interval)
208            .field("watchdog_timeout", &self.watchdog_timeout)
209            .field("rotation_interval", &self.rotation_interval)
210            .field("reconnect_base_delay", &self.reconnect_base_delay)
211            .field("reconnect_max_delay", &self.reconnect_max_delay)
212            .field("long_backoff", &self.long_backoff)
213            .field("quota_reconnect", &self.quota_reconnect)
214            .field("quota_reconnect_interval", &self.quota_reconnect_interval)
215            .field("search_failed_threshold", &self.search_failed_threshold)
216            .field("dedupe_cache_size", &self.dedupe_cache_size)
217            .field("max_message_bytes", &self.max_message_bytes)
218            .field("connect_timeout", &self.connect_timeout)
219            .field("http_client", &self.http_client.as_ref().map(|_| "custom"))
220            .field(
221                "ws_connector",
222                &self.ws_connector.as_ref().map(|_| "custom"),
223            )
224            .finish()
225    }
226}
227
228/// Builder of [`Config`].
229#[derive(Debug, Clone)]
230pub struct ConfigBuilder(Config);
231
232macro_rules! setters {
233    ($( $(#[$m:meta])* $name:ident : $ty:ty ),* $(,)?) => {
234        $(
235            $(#[$m])*
236            pub fn $name(mut self, value: $ty) -> Self {
237                self.0.$name = value;
238                self
239            }
240        )*
241    };
242}
243
244impl ConfigBuilder {
245    /// REST base URL.
246    pub fn base_url(mut self, value: impl Into<String>) -> Self {
247        self.0.base_url = value.into();
248        self
249    }
250
251    /// WebSocket URL.
252    pub fn wss_url(mut self, value: impl Into<String>) -> Self {
253        self.0.wss_url = value.into();
254        self
255    }
256
257    /// Upper bound of one REST call.
258    pub fn total_timeout(mut self, value: Duration) -> Self {
259        self.0.total_timeout = Some(value);
260        self
261    }
262
263    /// Your own `reqwest::Client` for REST (its own timeouts apply).
264    pub fn http_client(mut self, value: reqwest::Client) -> Self {
265        self.0.http_client = Some(value);
266        self
267    }
268
269    /// Your own transport for WebSocket dials.
270    pub fn ws_connector(mut self, value: impl WsConnector) -> Self {
271        self.0.ws_connector = Some(Arc::new(value));
272        self
273    }
274
275    setters! {
276        /// Timeout of one REST attempt.
277        timeout: Duration,
278        /// Retries for 5xx, network errors and attempt timeouts.
279        max_retries: u32,
280        /// First backoff delay.
281        retry_base_delay: Duration,
282        /// Largest backoff delay.
283        retry_max_delay: Duration,
284        /// Behaviour on a 429 `burst`.
285        retry_on_burst: RetryOnBurst,
286        /// Wait on a 429 `burst` without `Retry-After`.
287        burst_wait: Duration,
288        /// Page limit of `search_all`.
289        max_pages: u32,
290        /// Largest REST response body read.
291        max_response_bytes: usize,
292        /// Interval of the stream ping.
293        ping_interval: Duration,
294        /// Pong watchdog of streams.
295        watchdog_timeout: Duration,
296        /// Connection renewal of streams.
297        rotation_interval: Duration,
298        /// First reconnect delay.
299        reconnect_base_delay: Duration,
300        /// Largest reconnect delay.
301        reconnect_max_delay: Duration,
302        /// Wait after a dial refused for the connection limit.
303        long_backoff: Duration,
304        /// Redial while the WebSocket quota is used up (default `true`).
305        quota_reconnect: bool,
306        /// Interval of quota redials.
307        quota_reconnect_interval: Duration,
308        /// `SEARCH_FAILED` in a row before `on_error`.
309        search_failed_threshold: u32,
310        /// Entries of the duplicate filter of each stream.
311        dedupe_cache_size: usize,
312        /// Largest incoming stream message (at least 16 MiB).
313        max_message_bytes: usize,
314        /// Timeout of the WebSocket dial.
315        connect_timeout: Duration,
316    }
317
318    /// Checks the configuration and returns it.
319    pub fn build(self) -> Result<Config> {
320        self.0.validate()?;
321        Ok(self.0)
322    }
323}