1use std::fmt;
4use std::future::Future;
5use std::pin::Pin;
6#[cfg(not(target_arch = "wasm32"))]
7use std::sync::Arc;
8use std::time::Duration;
9
10#[cfg(not(target_arch = "wasm32"))]
11use tokio_tungstenite::tungstenite::client::IntoClientRequest;
12#[cfg(not(target_arch = "wasm32"))]
13use tokio_tungstenite::tungstenite::handshake::client::Request;
14#[cfg(not(target_arch = "wasm32"))]
15use tokio_tungstenite::tungstenite::http::HeaderValue;
16
17use crate::error::Error;
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum Format {
23 #[default]
25 Json,
26 Msgpack,
28}
29
30#[derive(Clone, Debug)]
32#[non_exhaustive]
33pub struct Reconnect {
34 pub enabled: bool,
36 pub base_delay: Duration,
38 pub max_delay: Duration,
40 pub factor: f64,
42 pub jitter: bool,
45 pub max_attempts: Option<u32>,
47}
48
49impl Default for Reconnect {
50 fn default() -> Self {
51 Self {
52 enabled: true,
53 base_delay: Duration::from_secs(1),
54 max_delay: Duration::from_secs(30),
55 factor: 1.5,
56 jitter: true,
57 max_attempts: None,
58 }
59 }
60}
61
62impl Reconnect {
63 pub(crate) fn delay(&self, attempt: u32) -> Duration {
65 let base = self.base_delay.as_secs_f64();
66 let exp = self.factor.max(1.0).powi(attempt.min(1000) as i32);
67 let mut secs = (base * exp).min(self.max_delay.as_secs_f64());
68 if !secs.is_finite() {
69 secs = self.max_delay.as_secs_f64();
70 }
71 if self.jitter {
72 secs += secs * 0.2 * (random() - 0.5);
73 }
74 Duration::from_secs_f64(secs.clamp(0.0, 300.0))
75 }
76}
77
78#[cfg(feature = "aws-lc")]
82#[derive(Clone, Debug)]
83#[non_exhaustive]
84pub struct Encryption {
85 pub server_keys: Vec<String>,
89 pub unauthenticated: bool,
92 pub bind_session: bool,
99}
100
101#[cfg(feature = "aws-lc")]
102impl Default for Encryption {
103 fn default() -> Self {
104 Self {
105 server_keys: Vec::new(),
106 unauthenticated: false,
107 bind_session: true,
108 }
109 }
110}
111
112#[cfg(feature = "aws-lc")]
113impl Encryption {
114 pub fn pinned<I, K>(server_keys: I) -> Self
116 where
117 I: IntoIterator<Item = K>,
118 K: Into<String>,
119 {
120 Self {
121 server_keys: server_keys.into_iter().map(Into::into).collect(),
122 ..Self::default()
123 }
124 }
125
126 pub fn unauthenticated() -> Self {
128 Self {
129 unauthenticated: true,
130 ..Self::default()
131 }
132 }
133}
134
135#[cfg(not(target_arch = "wasm32"))]
137fn random() -> f64 {
138 fastrand::f64()
139}
140
141#[cfg(target_arch = "wasm32")]
142fn random() -> f64 {
143 js_sys::Math::random()
144}
145
146#[cfg(not(target_arch = "wasm32"))]
147type TokenFuture = Pin<Box<dyn Future<Output = Result<String, String>> + Send>>;
148#[cfg(target_arch = "wasm32")]
149type TokenFuture = Pin<Box<dyn Future<Output = Result<String, String>>>>;
150
151#[derive(Clone)]
156#[cfg(not(target_arch = "wasm32"))]
157pub struct TokenProvider(Arc<dyn Fn() -> TokenFuture + Send + Sync>);
158
159#[derive(Clone)]
164#[cfg(target_arch = "wasm32")]
165pub struct TokenProvider(std::rc::Rc<dyn Fn() -> TokenFuture>);
166
167#[cfg(not(target_arch = "wasm32"))]
168impl TokenProvider {
169 pub fn new<F, Fut, E>(provider: F) -> Self
170 where
171 F: Fn() -> Fut + Send + Sync + 'static,
172 Fut: Future<Output = Result<String, E>> + Send + 'static,
173 E: fmt::Display,
174 {
175 Self(Arc::new(move || {
176 let token = provider();
177 Box::pin(async move { token.await.map_err(|e| e.to_string()) })
178 }))
179 }
180}
181
182#[cfg(target_arch = "wasm32")]
183impl TokenProvider {
184 pub fn new<F, Fut, E>(provider: F) -> Self
185 where
186 F: Fn() -> Fut + 'static,
187 Fut: Future<Output = Result<String, E>> + 'static,
188 E: fmt::Display,
189 {
190 Self(std::rc::Rc::new(move || {
191 let token = provider();
192 Box::pin(async move { token.await.map_err(|e| e.to_string()) })
193 }))
194 }
195}
196
197impl TokenProvider {
198 pub(crate) async fn token(&self) -> Result<String, String> {
199 (self.0)().await
200 }
201}
202
203impl fmt::Debug for TokenProvider {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 f.write_str("TokenProvider")
206 }
207}
208
209pub(crate) type Committed = std::sync::Arc<
214 dyn Fn(
215 Option<&str>,
216 ) -> Option<std::collections::BTreeMap<String, Vec<crate::message::Position>>>
217 + Send
218 + Sync,
219>;
220
221#[derive(Clone)]
225#[non_exhaustive]
226pub struct Config {
227 pub url: String,
229 pub token: Option<String>,
233 pub token_provider: Option<TokenProvider>,
238 pub cookie_name: String,
240 pub topics: Vec<String>,
243 pub format: Format,
245 pub compression: bool,
247 pub max_message_size: usize,
249 pub connect_timeout: Duration,
251 pub ready_timeout: Duration,
253 pub heartbeat: Duration,
255 pub idle_timeout: Duration,
258 pub recovery_timeout: Duration,
261 pub reconnect: Reconnect,
262 pub headers: Vec<(String, String)>,
265 pub send_queue: usize,
272 #[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
282 pub tls: Option<Arc<dyn std::any::Any + Send + Sync>>,
283 #[cfg(feature = "aws-lc")]
285 pub encryption: Option<Encryption>,
286 pub delivery: Option<crate::Delivery>,
291 pub offline: Option<crate::Offline>,
298 pub(crate) committed: Option<Committed>,
301 pub(crate) paused: Vec<String>,
304 pub(crate) tags: Option<std::sync::Arc<dyn crate::outbox::Tags>>,
307 #[cfg(feature = "aws-lc")]
312 pub signing_key: Option<Vec<u8>>,
313 #[cfg(feature = "aws-lc")]
318 pub server_signing_keys: Vec<String>,
319}
320
321const MAX_SEND_QUEUE: usize = 1 << 20;
323const MAX_WAIT: Duration = Duration::from_secs(7 * 86_400);
325
326impl fmt::Debug for Config {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 let redacted = |set: bool| if set { "Some(<redacted>)" } else { "None" };
329 let headers: Vec<(&str, &str)> = self
330 .headers
331 .iter()
332 .map(|(name, _)| (name.as_str(), "<redacted>"))
333 .collect();
334 let mut f = f.debug_struct("Config");
335 f.field("url", &self.url)
336 .field("token", &format_args!("{}", redacted(self.token.is_some())))
337 .field("token_provider", &self.token_provider)
338 .field("cookie_name", &self.cookie_name)
339 .field("topics", &self.topics)
340 .field("format", &self.format)
341 .field("compression", &self.compression)
342 .field("max_message_size", &self.max_message_size)
343 .field("connect_timeout", &self.connect_timeout)
344 .field("ready_timeout", &self.ready_timeout)
345 .field("heartbeat", &self.heartbeat)
346 .field("idle_timeout", &self.idle_timeout)
347 .field("recovery_timeout", &self.recovery_timeout)
348 .field("reconnect", &self.reconnect)
349 .field("headers", &headers)
350 .field("send_queue", &self.send_queue)
351 .field("delivery", &self.delivery)
352 .field("offline", &self.offline);
353 #[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
354 f.field(
355 "tls",
356 &format_args!(
357 "{}",
358 if self.tls.is_some() {
359 "Some(..)"
360 } else {
361 "None"
362 }
363 ),
364 );
365 #[cfg(feature = "aws-lc")]
366 f.field("encryption", &self.encryption)
367 .field(
368 "signing_key",
369 &format_args!("{}", redacted(self.signing_key.is_some())),
370 )
371 .field("server_signing_keys", &self.server_signing_keys);
372 f.finish()
373 }
374}
375
376impl Config {
377 pub fn new(url: impl Into<String>) -> Self {
378 Self {
379 url: url.into(),
380 token: None,
381 token_provider: None,
382 cookie_name: "access_token".to_owned(),
383 topics: Vec::new(),
384 format: Format::Json,
385 compression: true,
386 max_message_size: 16 * 1024 * 1024,
387 connect_timeout: Duration::from_secs(10),
388 ready_timeout: Duration::from_secs(10),
389 heartbeat: Duration::from_secs(15),
390 idle_timeout: Duration::from_secs(40),
391 recovery_timeout: Duration::from_secs(3),
392 reconnect: Reconnect::default(),
393 headers: Vec::new(),
394 send_queue: 1024,
395 #[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
396 tls: None,
397 #[cfg(feature = "aws-lc")]
398 encryption: None,
399 delivery: None,
400 offline: Some(crate::Offline::in_memory()),
401 committed: None,
402 paused: Vec::new(),
403 tags: None,
404 #[cfg(feature = "aws-lc")]
405 signing_key: None,
406 #[cfg(feature = "aws-lc")]
407 server_signing_keys: Vec::new(),
408 }
409 }
410
411 pub(crate) fn check(&self) -> Result<(), Error> {
413 let scheme = self.url.split_once("://").map(|(scheme, _)| scheme);
414 match scheme {
415 Some("ws") => {}
416 Some("wss") if cfg!(any(feature = "aws-lc", target_arch = "wasm32")) => {}
417 Some("wss") => {
418 return Err(Error::Config(
419 "wss:// needs the aws-lc feature (TLS)".to_owned(),
420 ));
421 }
422 _ => {
423 return Err(Error::Config(format!(
424 "{} is not a ws:// or wss:// URL",
425 self.url
426 )));
427 }
428 }
429 if self.heartbeat.is_zero() || self.idle_timeout <= self.heartbeat {
430 return Err(Error::Config(
431 "heartbeat must be above zero and below idle_timeout".to_owned(),
432 ));
433 }
434 if !(1..=MAX_SEND_QUEUE).contains(&self.send_queue) {
435 return Err(Error::Config(format!(
436 "send_queue must be 1 to {MAX_SEND_QUEUE}"
437 )));
438 }
439 if self.max_message_size == 0 {
440 return Err(Error::Config(
441 "max_message_size must be above zero".to_owned(),
442 ));
443 }
444 for (name, wait) in [
447 ("connect_timeout", self.connect_timeout),
448 ("ready_timeout", self.ready_timeout),
449 ("heartbeat", self.heartbeat),
450 ("idle_timeout", self.idle_timeout),
451 ("recovery_timeout", self.recovery_timeout),
452 ] {
453 if wait > MAX_WAIT {
454 return Err(Error::Config(format!("{name} must be at most a week")));
455 }
456 }
457 #[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
458 if self
459 .tls
460 .as_ref()
461 .is_some_and(|tls| !tls.is::<rustls::ClientConfig>())
462 {
463 return Err(Error::Config(
464 "tls must be an Arc of a rustls::ClientConfig (rustls 0.23)".to_owned(),
465 ));
466 }
467 #[cfg(not(target_arch = "wasm32"))]
468 self.request(None, false)?;
469 Ok(())
470 }
471
472 pub(crate) fn url(&self, e2e: bool) -> String {
474 let mut url = self.url.clone();
475 let mut param = |kv: &str| {
476 url.push(if url.contains('?') { '&' } else { '?' });
477 url.push_str(kv);
478 };
479 param(concat!("client_version=", env!("CARGO_PKG_VERSION")));
480 param("protocol_version=1");
481 if self.format == Format::Msgpack {
482 param("format=msgpack");
483 }
484 if !self.compression {
485 param("compression=false");
486 }
487 if e2e {
488 param("e2e=1");
489 }
490 url
491 }
492
493 #[cfg(not(target_arch = "wasm32"))]
496 pub(crate) fn request(&self, token: Option<&str>, e2e: bool) -> Result<Request, Error> {
497 let mut request = self
498 .url(e2e)
499 .into_client_request()
500 .map_err(|e| Error::Config(format!("{}: {e}", self.url)))?;
501 let headers = request.headers_mut();
502 for (name, value) in &self.headers {
503 let name = name
504 .parse::<tokio_tungstenite::tungstenite::http::HeaderName>()
505 .map_err(|e| Error::Config(format!("header {name}: {e}")))?;
506 let value = HeaderValue::from_str(value)
507 .map_err(|e| Error::Config(format!("header {name}: {e}")))?;
508 headers.append(name, value);
509 }
510 if let Some(token) = token.filter(|t| !t.is_empty()) {
511 let cookie = match headers.get("cookie").and_then(|v| v.to_str().ok()) {
512 Some(cookies) => format!("{cookies}; {}={token}", self.cookie_name),
513 None => format!("{}={token}", self.cookie_name),
514 };
515 let cookie = HeaderValue::from_str(&cookie)
516 .map_err(|_| Error::Config("the token cannot go in a cookie".to_owned()))?;
517 headers.insert("cookie", cookie);
518 if !headers.contains_key("authorization") {
519 let bearer = HeaderValue::from_str(&format!("Bearer {token}"))
520 .map_err(|_| Error::Config("the token cannot go in a header".to_owned()))?;
521 headers.insert("authorization", bearer);
522 }
523 }
524 Ok(request)
525 }
526}
527
528#[cfg(test)]
529mod tests {
530 use super::*;
531
532 #[test]
533 #[cfg(not(target_arch = "wasm32"))]
534 fn the_request_carries_the_token_and_the_wishes() {
535 let mut config = Config::new("ws://127.0.0.1:5006/wse?room=1");
536 config.format = Format::Msgpack;
537 config.compression = false;
538 config.headers = vec![("Cookie".into(), "theme=dark".into())];
539 let request = config.request(Some("jwt"), true).unwrap();
540 let query = request.uri().query().unwrap();
541 assert!(query.starts_with("room=1&client_version="), "{query}");
542 assert!(
543 query.contains("&format=msgpack&compression=false&e2e=1"),
544 "{query}"
545 );
546 assert_eq!(request.headers()["cookie"], "theme=dark; access_token=jwt");
547 assert_eq!(request.headers()["authorization"], "Bearer jwt");
548 }
549
550 #[test]
551 fn a_configuration_that_cannot_work_is_refused() {
552 assert!(Config::new("http://example.com").check().is_err());
553 assert!(Config::new("example.com").check().is_err());
554 let mut config = Config::new("ws://example.com/wse");
555 config.idle_timeout = config.heartbeat;
556 assert!(config.check().is_err());
557 assert!(Config::new("ws://example.com/wse").check().is_ok());
558 }
559
560 #[test]
561 fn waits_grow_to_the_cap() {
562 let mut reconnect = Reconnect {
563 jitter: false,
564 ..Reconnect::default()
565 };
566 assert_eq!(reconnect.delay(0), Duration::from_secs(1));
567 assert_eq!(reconnect.delay(1), Duration::from_millis(1500));
568 assert_eq!(reconnect.delay(50), Duration::from_secs(30));
569 assert_eq!(reconnect.delay(u32::MAX), Duration::from_secs(30));
570 reconnect.jitter = true;
571 let d = reconnect.delay(0).as_secs_f64();
572 assert!((0.9..=1.1).contains(&d), "{d}");
573 }
574}