1use std::fmt;
2use std::sync::Arc;
3use std::time::Duration;
4
5use crate::error::{Error, Result};
6use crate::ws::WsConnector;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10#[non_exhaustive]
11pub enum RetryOnBurst {
12 #[default]
15 Once,
16 Off,
18}
19
20#[derive(Clone)]
24#[non_exhaustive]
25pub struct Config {
26 api_key: String,
27 pub base_url: String,
29 pub wss_url: String,
31 pub timeout: Duration,
33 pub total_timeout: Option<Duration>,
35 pub max_retries: u32,
37 pub retry_base_delay: Duration,
39 pub retry_max_delay: Duration,
41 pub retry_on_burst: RetryOnBurst,
43 pub burst_wait: Duration,
45 pub max_pages: u32,
47 pub max_response_bytes: usize,
49 pub ping_interval: Duration,
51 pub watchdog_timeout: Duration,
53 pub rotation_interval: Duration,
55 pub reconnect_base_delay: Duration,
57 pub reconnect_max_delay: Duration,
59 pub long_backoff: Duration,
61 pub quota_reconnect: bool,
64 pub quota_reconnect_interval: Duration,
66 pub search_failed_threshold: u32,
68 pub dedupe_cache_size: usize,
70 pub max_message_bytes: usize,
72 pub connect_timeout: Duration,
74 pub http_client: Option<reqwest::Client>,
76 pub ws_connector: Option<Arc<dyn WsConnector>>,
78}
79
80impl Config {
81 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 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 pub(crate) fn rest_base(&self) -> &str {
177 self.base_url.trim_end_matches('/')
178 }
179
180 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 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#[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 pub fn base_url(mut self, value: impl Into<String>) -> Self {
247 self.0.base_url = value.into();
248 self
249 }
250
251 pub fn wss_url(mut self, value: impl Into<String>) -> Self {
253 self.0.wss_url = value.into();
254 self
255 }
256
257 pub fn total_timeout(mut self, value: Duration) -> Self {
259 self.0.total_timeout = Some(value);
260 self
261 }
262
263 pub fn http_client(mut self, value: reqwest::Client) -> Self {
265 self.0.http_client = Some(value);
266 self
267 }
268
269 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: Duration,
278 max_retries: u32,
280 retry_base_delay: Duration,
282 retry_max_delay: Duration,
284 retry_on_burst: RetryOnBurst,
286 burst_wait: Duration,
288 max_pages: u32,
290 max_response_bytes: usize,
292 ping_interval: Duration,
294 watchdog_timeout: Duration,
296 rotation_interval: Duration,
298 reconnect_base_delay: Duration,
300 reconnect_max_delay: Duration,
302 long_backoff: Duration,
304 quota_reconnect: bool,
306 quota_reconnect_interval: Duration,
308 search_failed_threshold: u32,
310 dedupe_cache_size: usize,
312 max_message_bytes: usize,
314 connect_timeout: Duration,
316 }
317
318 pub fn build(self) -> Result<Config> {
320 self.0.validate()?;
321 Ok(self.0)
322 }
323}