use std::fmt;
use std::future::Future;
use std::pin::Pin;
#[cfg(not(target_arch = "wasm32"))]
use std::sync::Arc;
use std::time::Duration;
#[cfg(not(target_arch = "wasm32"))]
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
#[cfg(not(target_arch = "wasm32"))]
use tokio_tungstenite::tungstenite::handshake::client::Request;
#[cfg(not(target_arch = "wasm32"))]
use tokio_tungstenite::tungstenite::http::HeaderValue;
use crate::error::Error;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Format {
#[default]
Json,
Msgpack,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Reconnect {
pub enabled: bool,
pub base_delay: Duration,
pub max_delay: Duration,
pub factor: f64,
pub jitter: bool,
pub max_attempts: Option<u32>,
}
impl Default for Reconnect {
fn default() -> Self {
Self {
enabled: true,
base_delay: Duration::from_secs(1),
max_delay: Duration::from_secs(30),
factor: 1.5,
jitter: true,
max_attempts: None,
}
}
}
impl Reconnect {
pub(crate) fn delay(&self, attempt: u32) -> Duration {
let base = self.base_delay.as_secs_f64();
let exp = self.factor.max(1.0).powi(attempt.min(1000) as i32);
let mut secs = (base * exp).min(self.max_delay.as_secs_f64());
if !secs.is_finite() {
secs = self.max_delay.as_secs_f64();
}
if self.jitter {
secs += secs * 0.2 * (random() - 0.5);
}
Duration::from_secs_f64(secs.clamp(0.0, 300.0))
}
}
#[cfg(feature = "aws-lc")]
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Encryption {
pub server_keys: Vec<String>,
pub unauthenticated: bool,
pub bind_session: bool,
}
#[cfg(feature = "aws-lc")]
impl Default for Encryption {
fn default() -> Self {
Self {
server_keys: Vec::new(),
unauthenticated: false,
bind_session: true,
}
}
}
#[cfg(feature = "aws-lc")]
impl Encryption {
pub fn pinned<I, K>(server_keys: I) -> Self
where
I: IntoIterator<Item = K>,
K: Into<String>,
{
Self {
server_keys: server_keys.into_iter().map(Into::into).collect(),
..Self::default()
}
}
pub fn unauthenticated() -> Self {
Self {
unauthenticated: true,
..Self::default()
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn random() -> f64 {
fastrand::f64()
}
#[cfg(target_arch = "wasm32")]
fn random() -> f64 {
js_sys::Math::random()
}
#[cfg(not(target_arch = "wasm32"))]
type TokenFuture = Pin<Box<dyn Future<Output = Result<String, String>> + Send>>;
#[cfg(target_arch = "wasm32")]
type TokenFuture = Pin<Box<dyn Future<Output = Result<String, String>>>>;
#[derive(Clone)]
#[cfg(not(target_arch = "wasm32"))]
pub struct TokenProvider(Arc<dyn Fn() -> TokenFuture + Send + Sync>);
#[derive(Clone)]
#[cfg(target_arch = "wasm32")]
pub struct TokenProvider(std::rc::Rc<dyn Fn() -> TokenFuture>);
#[cfg(not(target_arch = "wasm32"))]
impl TokenProvider {
pub fn new<F, Fut, E>(provider: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<String, E>> + Send + 'static,
E: fmt::Display,
{
Self(Arc::new(move || {
let token = provider();
Box::pin(async move { token.await.map_err(|e| e.to_string()) })
}))
}
}
#[cfg(target_arch = "wasm32")]
impl TokenProvider {
pub fn new<F, Fut, E>(provider: F) -> Self
where
F: Fn() -> Fut + 'static,
Fut: Future<Output = Result<String, E>> + 'static,
E: fmt::Display,
{
Self(std::rc::Rc::new(move || {
let token = provider();
Box::pin(async move { token.await.map_err(|e| e.to_string()) })
}))
}
}
impl TokenProvider {
pub(crate) async fn token(&self) -> Result<String, String> {
(self.0)().await
}
}
impl fmt::Debug for TokenProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("TokenProvider")
}
}
pub(crate) type Committed = std::sync::Arc<
dyn Fn(
Option<&str>,
) -> Option<std::collections::BTreeMap<String, Vec<crate::message::Position>>>
+ Send
+ Sync,
>;
#[derive(Clone)]
#[non_exhaustive]
pub struct Config {
pub url: String,
pub token: Option<String>,
pub token_provider: Option<TokenProvider>,
pub cookie_name: String,
pub topics: Vec<String>,
pub format: Format,
pub compression: bool,
pub max_message_size: usize,
pub connect_timeout: Duration,
pub ready_timeout: Duration,
pub heartbeat: Duration,
pub idle_timeout: Duration,
pub recovery_timeout: Duration,
pub reconnect: Reconnect,
pub headers: Vec<(String, String)>,
pub send_queue: usize,
#[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
pub tls: Option<Arc<dyn std::any::Any + Send + Sync>>,
#[cfg(feature = "aws-lc")]
pub encryption: Option<Encryption>,
pub(crate) committed: Option<Committed>,
#[cfg(feature = "aws-lc")]
pub signing_key: Option<Vec<u8>>,
#[cfg(feature = "aws-lc")]
pub server_signing_keys: Vec<String>,
}
const MAX_SEND_QUEUE: usize = 1 << 20;
const MAX_WAIT: Duration = Duration::from_secs(7 * 86_400);
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let redacted = |set: bool| if set { "Some(<redacted>)" } else { "None" };
let headers: Vec<(&str, &str)> = self
.headers
.iter()
.map(|(name, _)| (name.as_str(), "<redacted>"))
.collect();
let mut f = f.debug_struct("Config");
f.field("url", &self.url)
.field("token", &format_args!("{}", redacted(self.token.is_some())))
.field("token_provider", &self.token_provider)
.field("cookie_name", &self.cookie_name)
.field("topics", &self.topics)
.field("format", &self.format)
.field("compression", &self.compression)
.field("max_message_size", &self.max_message_size)
.field("connect_timeout", &self.connect_timeout)
.field("ready_timeout", &self.ready_timeout)
.field("heartbeat", &self.heartbeat)
.field("idle_timeout", &self.idle_timeout)
.field("recovery_timeout", &self.recovery_timeout)
.field("reconnect", &self.reconnect)
.field("headers", &headers)
.field("send_queue", &self.send_queue);
#[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
f.field(
"tls",
&format_args!(
"{}",
if self.tls.is_some() {
"Some(..)"
} else {
"None"
}
),
);
#[cfg(feature = "aws-lc")]
f.field("encryption", &self.encryption)
.field(
"signing_key",
&format_args!("{}", redacted(self.signing_key.is_some())),
)
.field("server_signing_keys", &self.server_signing_keys);
f.finish()
}
}
impl Config {
pub fn new(url: impl Into<String>) -> Self {
Self {
url: url.into(),
token: None,
token_provider: None,
cookie_name: "access_token".to_owned(),
topics: Vec::new(),
format: Format::Json,
compression: true,
max_message_size: 16 * 1024 * 1024,
connect_timeout: Duration::from_secs(10),
ready_timeout: Duration::from_secs(10),
heartbeat: Duration::from_secs(15),
idle_timeout: Duration::from_secs(40),
recovery_timeout: Duration::from_secs(3),
reconnect: Reconnect::default(),
headers: Vec::new(),
send_queue: 1024,
#[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
tls: None,
#[cfg(feature = "aws-lc")]
encryption: None,
committed: None,
#[cfg(feature = "aws-lc")]
signing_key: None,
#[cfg(feature = "aws-lc")]
server_signing_keys: Vec::new(),
}
}
pub(crate) fn check(&self) -> Result<(), Error> {
let scheme = self.url.split_once("://").map(|(scheme, _)| scheme);
match scheme {
Some("ws") => {}
Some("wss") if cfg!(any(feature = "aws-lc", target_arch = "wasm32")) => {}
Some("wss") => {
return Err(Error::Config(
"wss:// needs the aws-lc feature (TLS)".to_owned(),
));
}
_ => {
return Err(Error::Config(format!(
"{} is not a ws:// or wss:// URL",
self.url
)));
}
}
if self.heartbeat.is_zero() || self.idle_timeout <= self.heartbeat {
return Err(Error::Config(
"heartbeat must be above zero and below idle_timeout".to_owned(),
));
}
if !(1..=MAX_SEND_QUEUE).contains(&self.send_queue) {
return Err(Error::Config(format!(
"send_queue must be 1 to {MAX_SEND_QUEUE}"
)));
}
if self.max_message_size == 0 {
return Err(Error::Config(
"max_message_size must be above zero".to_owned(),
));
}
for (name, wait) in [
("connect_timeout", self.connect_timeout),
("ready_timeout", self.ready_timeout),
("heartbeat", self.heartbeat),
("idle_timeout", self.idle_timeout),
("recovery_timeout", self.recovery_timeout),
] {
if wait > MAX_WAIT {
return Err(Error::Config(format!("{name} must be at most a week")));
}
}
#[cfg(all(feature = "aws-lc", not(target_arch = "wasm32")))]
if self
.tls
.as_ref()
.is_some_and(|tls| !tls.is::<rustls::ClientConfig>())
{
return Err(Error::Config(
"tls must be an Arc of a rustls::ClientConfig (rustls 0.23)".to_owned(),
));
}
#[cfg(not(target_arch = "wasm32"))]
self.request(None, false)?;
Ok(())
}
pub(crate) fn url(&self, e2e: bool) -> String {
let mut url = self.url.clone();
let mut param = |kv: &str| {
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(kv);
};
param(concat!("client_version=", env!("CARGO_PKG_VERSION")));
param("protocol_version=1");
if self.format == Format::Msgpack {
param("format=msgpack");
}
if !self.compression {
param("compression=false");
}
if e2e {
param("e2e=1");
}
url
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn request(&self, token: Option<&str>, e2e: bool) -> Result<Request, Error> {
let mut request = self
.url(e2e)
.into_client_request()
.map_err(|e| Error::Config(format!("{}: {e}", self.url)))?;
let headers = request.headers_mut();
for (name, value) in &self.headers {
let name = name
.parse::<tokio_tungstenite::tungstenite::http::HeaderName>()
.map_err(|e| Error::Config(format!("header {name}: {e}")))?;
let value = HeaderValue::from_str(value)
.map_err(|e| Error::Config(format!("header {name}: {e}")))?;
headers.append(name, value);
}
if let Some(token) = token.filter(|t| !t.is_empty()) {
let cookie = match headers.get("cookie").and_then(|v| v.to_str().ok()) {
Some(cookies) => format!("{cookies}; {}={token}", self.cookie_name),
None => format!("{}={token}", self.cookie_name),
};
let cookie = HeaderValue::from_str(&cookie)
.map_err(|_| Error::Config("the token cannot go in a cookie".to_owned()))?;
headers.insert("cookie", cookie);
if !headers.contains_key("authorization") {
let bearer = HeaderValue::from_str(&format!("Bearer {token}"))
.map_err(|_| Error::Config("the token cannot go in a header".to_owned()))?;
headers.insert("authorization", bearer);
}
}
Ok(request)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn the_request_carries_the_token_and_the_wishes() {
let mut config = Config::new("ws://127.0.0.1:5006/wse?room=1");
config.format = Format::Msgpack;
config.compression = false;
config.headers = vec![("Cookie".into(), "theme=dark".into())];
let request = config.request(Some("jwt"), true).unwrap();
let query = request.uri().query().unwrap();
assert!(query.starts_with("room=1&client_version="), "{query}");
assert!(
query.contains("&format=msgpack&compression=false&e2e=1"),
"{query}"
);
assert_eq!(request.headers()["cookie"], "theme=dark; access_token=jwt");
assert_eq!(request.headers()["authorization"], "Bearer jwt");
}
#[test]
fn a_configuration_that_cannot_work_is_refused() {
assert!(Config::new("http://example.com").check().is_err());
assert!(Config::new("example.com").check().is_err());
let mut config = Config::new("ws://example.com/wse");
config.idle_timeout = config.heartbeat;
assert!(config.check().is_err());
assert!(Config::new("ws://example.com/wse").check().is_ok());
}
#[test]
fn waits_grow_to_the_cap() {
let mut reconnect = Reconnect {
jitter: false,
..Reconnect::default()
};
assert_eq!(reconnect.delay(0), Duration::from_secs(1));
assert_eq!(reconnect.delay(1), Duration::from_millis(1500));
assert_eq!(reconnect.delay(50), Duration::from_secs(30));
assert_eq!(reconnect.delay(u32::MAX), Duration::from_secs(30));
reconnect.jitter = true;
let d = reconnect.delay(0).as_secs_f64();
assert!((0.9..=1.1).contains(&d), "{d}");
}
}