Skip to main content

wse_client/
config.rs

1//! What a client connects to and how it behaves.
2
3use 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/// The wire format the server sends this client.
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum Format {
23    /// JSON (the default).
24    #[default]
25    Json,
26    /// MessagePack: 24-41% fewer bytes on typical messages.
27    Msgpack,
28}
29
30/// How a lost connection is made again.
31#[derive(Clone, Debug)]
32#[non_exhaustive]
33pub struct Reconnect {
34    /// Reconnect at all; without it a lost connection ends the client.
35    pub enabled: bool,
36    /// The wait before the first attempt.
37    pub base_delay: Duration,
38    /// The longest wait between attempts.
39    pub max_delay: Duration,
40    /// Each attempt waits this many times longer than the one before.
41    pub factor: f64,
42    /// Spread waits by ±10%, so clients of a restarted server do not all
43    /// come back at once.
44    pub jitter: bool,
45    /// Attempts in a row before giving up; `None` never gives up.
46    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    /// The wait before attempt `attempt` (0 for the first).
64    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/// End-to-end encryption: a session with the server inside the
79/// connection, so whatever terminates TLS in between (a proxy, a load
80/// balancer) sees nothing.
81#[cfg(feature = "aws-lc")]
82#[derive(Clone, Debug)]
83#[non_exhaustive]
84pub struct Encryption {
85    /// The server's identity public keys (base64 of the uncompressed
86    /// point, from the server's `e2e_identity_public_key`): its answer must
87    /// be signed by one of them.
88    pub server_keys: Vec<String>,
89    /// Without `server_keys`: go on with a server that does not sign.
90    /// Protects from passive observers only.
91    pub unauthenticated: bool,
92    /// With [`Config::signing_key`], the session is bound to it (true, the
93    /// default): the client proves the key inside the session, and goes on
94    /// only once the server confirms the session is bound to that key, as
95    /// its token names it (`cnf`). A token copied on the way then opens
96    /// nothing. False for a token that names no key, whose key the server
97    /// application binds itself (`set_client_key`).
98    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    /// A session with a server holding one of `server_keys`.
115    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    /// A session with whatever server answers.
127    pub fn unauthenticated() -> Self {
128        Self {
129            unauthenticated: true,
130            ..Self::default()
131        }
132    }
133}
134
135/// A number in [0, 1), for the jitter of the waits.
136#[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/// Fetches the token for each connection attempt, so an expired one is
152/// replaced without restarting the client. In the browser, which sends the
153/// page's cookies itself and no header, it is asked before each attempt (to
154/// refresh the cookie, say) and what it returns is not sent.
155#[derive(Clone)]
156#[cfg(not(target_arch = "wasm32"))]
157pub struct TokenProvider(Arc<dyn Fn() -> TokenFuture + Send + Sync>);
158
159/// Fetches the token for each connection attempt, so an expired one is
160/// replaced without restarting the client. In the browser, which sends the
161/// page's cookies itself and no header, it is asked before each attempt (to
162/// refresh the cookie, say) and what it returns is not sent.
163#[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
209/// What the application committed it applied: asked with the user of a
210/// connection about to subscribe, each topic's position in each of its
211/// streams. A topic left out starts with none; None leaves delivery where it
212/// is.
213pub(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/// What a client connects to and how it behaves. The defaults are those of
222/// the Python and TypeScript clients. Its `Debug` print leaves the token,
223/// the headers' values and the signing key out.
224#[derive(Clone)]
225#[non_exhaustive]
226pub struct Config {
227    /// `ws://host:port/wse` or `wss://...`.
228    pub url: String,
229    /// The JWT, sent in the `access_token` cookie and as
230    /// `Authorization: Bearer`. Not in the browser: it sends the page's
231    /// cookies itself, and no header.
232    pub token: Option<String>,
233    /// Asked for the token before each connection attempt (within
234    /// `connect_timeout`); takes the place of `token`. A refused token is
235    /// then fetched again instead of ending the client, three times at most
236    /// between two connections the server took.
237    pub token_provider: Option<TokenProvider>,
238    /// The cookie the token goes in: the server's `jwt_cookie_name`.
239    pub cookie_name: String,
240    /// Topics to subscribe to once connected, and again after every
241    /// reconnect from where the client left off.
242    pub topics: Vec<String>,
243    /// How the server sends this client its messages.
244    pub format: Format,
245    /// Let the server compress large messages (zlib, above 1 KiB).
246    pub compression: bool,
247    /// The largest message taken, also after inflating (16 MiB).
248    pub max_message_size: usize,
249    /// For the socket, TLS and the upgrade (10 s).
250    pub connect_timeout: Duration,
251    /// For the server to confirm the connection after the upgrade (10 s).
252    pub ready_timeout: Duration,
253    /// Between the client's heartbeats (15 s).
254    pub heartbeat: Duration,
255    /// Silence from the server after which the connection is taken for
256    /// dead and made again (40 s; the server pings every 25 s).
257    pub idle_timeout: Duration,
258    /// How long a topic waits for the server to replay messages it missed
259    /// before reporting the gap (3 s); zero reports it at once.
260    pub recovery_timeout: Duration,
261    pub reconnect: Reconnect,
262    /// More headers for the upgrade request (not in the browser, which
263    /// sends none).
264    pub headers: Vec<(String, String)>,
265    /// Messages waiting to be sent at most; past it `try_send` fails and
266    /// `send` waits (1024). What a lost connection did not write goes out
267    /// on the next one, once the server takes it. Sends that wait for their
268    /// topics ([`Client::send_requiring`](crate::Client::send_requiring))
269    /// are held besides, as many at most: while that many wait, so does the
270    /// queue.
271    pub send_queue: usize,
272    /// The TLS configuration for `wss://`: an `Arc` of a
273    /// `rustls::ClientConfig` of rustls 0.23, which this crate builds on,
274    /// held as `Any` so that rustls's own versions are not this crate's.
275    /// By default the Mozilla root certificates on aws-lc-rs. In the browser
276    /// TLS is the browser's.
277    ///
278    /// ```ignore
279    /// config.tls = Some(std::sync::Arc::new(my_rustls_client_config));
280    /// ```
281    #[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
282    pub tls: Option<Arc<dyn std::any::Any + Send + Sync>>,
283    /// End-to-end encryption; none by default.
284    #[cfg(feature = "aws-lc")]
285    pub encryption: Option<Encryption>,
286    /// The recover-or-resync delivery: a topic that is not continuous holds
287    /// its messages until the application brought its state up to date, and
288    /// recovery starts from what it committed. None: best effort, where the
289    /// topics' states and the checkpoint are kept all the same.
290    pub delivery: Option<crate::Delivery>,
291    /// The outbox: every message sent, except a live or signed one, waits
292    /// in it until the server answers for it, and goes again after a
293    /// reconnect; a server that answers (3.2) takes each once. In memory by
294    /// default; [`Offline::in_file`](crate::Offline::in_file) keeps it past
295    /// the application's end. None: no outbox, and a send with no
296    /// connection fails with [`Error::NotConnected`](crate::Error::NotConnected).
297    pub offline: Option<crate::Offline>,
298    /// Where each recovery starts: what the application committed, as the
299    /// delivery keeps it.
300    pub(crate) committed: Option<Committed>,
301    /// The reasons the client starts paused for: no connection is made until
302    /// they are cleared (the bridge's owner, until a window shares it).
303    pub(crate) paused: Vec<String>,
304    /// The bridge's owner: what became of its windows' sends, and whether a
305    /// window holds one back.
306    pub(crate) tags: Option<std::sync::Arc<dyn crate::outbox::Tags>>,
307    /// This client's ECDSA P-256 private key (PKCS#8, PEM or DER) for
308    /// [`Client::send_signed`](crate::Client::send_signed). The server
309    /// learns its public key from the token's `cnf` claim or from its
310    /// application.
311    #[cfg(feature = "aws-lc")]
312    pub signing_key: Option<Vec<u8>>,
313    /// The server's signing public keys (base64 of the uncompressed point,
314    /// from the server's `signing_public_key`) that the messages it signs
315    /// are checked against; one failing the check is dropped. Without them
316    /// signed messages are delivered unchecked.
317    #[cfg(feature = "aws-lc")]
318    pub server_signing_keys: Vec<String>,
319}
320
321/// Messages waiting to be sent at most.
322const MAX_SEND_QUEUE: usize = 1 << 20;
323/// The longest wait a client is configured with.
324const 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    /// Checks what can be checked before connecting.
412    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        // A week at most: further out, the timers' instants overflow, and the
445        // browser's cannot count past 24.8 days.
446        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    /// The URL, with what the client asks of the server in the query.
473    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    /// The upgrade request, with the token and what the client asks of the
494    /// server in the query.
495    #[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}