use tokio::sync::oneshot;
use crate::config::Config;
use crate::error::Error;
use crate::handler::Disconnected;
const AUTH_CLOSE_CODES: [u16; 3] = [4401, 4403, 1008];
const CLOSE_E2E_UNSUPPORTED: u16 = 4800;
const AUTH_ATTEMPTS: u32 = 3;
pub(crate) enum Lost {
Shutdown,
Requested,
Closed { code: Option<u16>, reason: String },
Failed(Error),
Fatal(Error),
}
pub(crate) enum Next {
Stop(Option<Error>),
Retry(Disconnected),
}
#[derive(Default)]
pub(crate) struct Policy {
attempts: u32,
auth_failures: u32,
}
pub(crate) type First = Option<oneshot::Sender<Result<(), Error>>>;
impl Policy {
pub(crate) fn connected(&mut self) {
self.attempts = 0;
self.auth_failures = 0;
}
pub(crate) fn after(&mut self, lost: Lost, config: &Config, first: &mut First) -> Next {
let (code, reason, error) = match lost {
Lost::Shutdown => return Next::Stop(None),
Lost::Requested => {
self.connected();
return Next::Retry(Disconnected {
code: None,
reason: "reconnect asked".to_owned(),
retry_in: std::time::Duration::ZERO,
attempt: 0,
});
}
Lost::Closed { code, reason } => {
let error = close_error(code, &reason);
(code, reason, error)
}
Lost::Failed(error) => (None, error.to_string(), error),
Lost::Fatal(error) => {
return match first.take() {
Some(first) => {
let _ = first.send(Err(error));
Next::Stop(None)
}
None => Next::Stop(Some(error)),
};
}
};
if let Some(first) = first.take() {
let _ = first.send(Err(error));
return Next::Stop(None);
}
match &error {
Error::Auth(_) => {
self.auth_failures += 1;
if config.token_provider.is_none() || self.auth_failures >= AUTH_ATTEMPTS {
return Next::Stop(Some(error));
}
}
Error::Encryption(_) | Error::Config(_) => return Next::Stop(Some(error)),
_ => {}
}
if !config.reconnect.enabled {
return Next::Stop(Some(error));
}
if let Some(max) = config.reconnect.max_attempts
&& self.attempts >= max
{
return Next::Stop(Some(Error::GaveUp(format!(
"{} attempt(s); last: {error}",
self.attempts
))));
}
let retry_in = config.reconnect.delay(self.attempts);
self.attempts += 1;
tracing::info!(
"[WSE] connection lost ({reason}); attempt {} in {retry_in:?}",
self.attempts
);
Next::Retry(Disconnected {
code,
reason,
retry_in,
attempt: self.attempts,
})
}
}
fn close_error(code: Option<u16>, reason: &str) -> Error {
let what = match code {
Some(code) if reason.is_empty() => format!("closed with {code}"),
Some(code) => format!("closed with {code}: {reason}"),
None => reason.to_owned(),
};
match code {
Some(code) if AUTH_CLOSE_CODES.contains(&code) => Error::Auth(what),
Some(CLOSE_E2E_UNSUPPORTED) => Error::Encryption(what),
_ => Error::Connect(what),
}
}