use std::future::Future;
use std::time::Duration;
use crate::error::Error;
use crate::message::{Message, Position};
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSend: Send {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Send> MaybeSend for T {}
#[cfg(target_arch = "wasm32")]
pub trait MaybeSend {}
#[cfg(target_arch = "wasm32")]
impl<T> MaybeSend for T {}
pub trait Handler: MaybeSend + 'static {
fn message(&mut self, message: &Message<'_>);
fn event(&mut self, event: Event) {
let _ = event;
}
fn binary(&mut self, data: &[u8]) {
let _ = data;
}
fn ready(&mut self) -> impl Future<Output = ()> + MaybeSend {
std::future::ready(())
}
}
impl<F> Handler for F
where
F: FnMut(&Message<'_>) + MaybeSend + 'static,
{
fn message(&mut self, message: &Message<'_>) {
self(message)
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Event {
Connected(Connected),
Disconnected(Disconnected),
Paused(Paused),
Subscribed(Subscribed),
Gap(Gap),
ServerError(ServerError),
Closed(Option<Error>),
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Connected {
pub connection_id: String,
pub user_id: Option<String>,
pub reconnected: bool,
pub recovery: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Disconnected {
pub code: Option<u16>,
pub reason: String,
pub retry_in: Duration,
pub attempt: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Paused {
pub reasons: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Subscribed {
pub topics: Vec<String>,
pub failed: Vec<String>,
pub recovery: Vec<Recovery>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Recovery {
pub topic: String,
pub recovered: bool,
pub count: u64,
pub position: Option<Position>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Gap {
pub topic: String,
pub epoch: u32,
pub first: Option<u64>,
pub last: Option<u64>,
pub reason: GapReason,
}
impl Gap {
pub fn missed(&self) -> Option<u64> {
Some(self.last?.checked_sub(self.first?)? + 1)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum GapReason {
Timeout,
Overflow,
NotRecovered,
Unavailable,
Incomplete,
EpochChanged,
Closed,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct ServerError {
pub code: String,
pub message: String,
pub details: serde_json::Value,
}