use std::collections::VecDeque;
use tokio::sync::mpsc;
use crate::client::Client;
use crate::config::Config;
use crate::error::Error;
use crate::handler::{Event, Handler};
use crate::message::{Message, OwnedMessage};
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Incoming {
Message(OwnedMessage),
Event(Event),
Binary(bytes::Bytes),
}
#[derive(Debug)]
pub struct Events {
rx: Receiver,
}
#[cfg(not(target_arch = "wasm32"))]
type Sender = mpsc::Sender<Incoming>;
#[cfg(not(target_arch = "wasm32"))]
type Receiver = mpsc::Receiver<Incoming>;
#[cfg(target_arch = "wasm32")]
type Sender = mpsc::UnboundedSender<Incoming>;
#[cfg(target_arch = "wasm32")]
type Receiver = mpsc::UnboundedReceiver<Incoming>;
impl Events {
pub async fn next(&mut self) -> Option<Incoming> {
self.rx.recv().await
}
}
impl futures_util::Stream for Events {
type Item = Incoming;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Incoming>> {
self.rx.poll_recv(cx)
}
}
#[cfg(not(target_arch = "wasm32"))]
const QUEUE: usize = 1024;
pub async fn connect(config: Config) -> Result<(Client, Events), Error> {
#[cfg(not(target_arch = "wasm32"))]
let (tx, rx) = mpsc::channel(QUEUE);
#[cfg(target_arch = "wasm32")]
let (tx, rx) = mpsc::unbounded_channel();
let queue = Queue {
tx,
waiting: VecDeque::new(),
};
let client = Client::connect(config, queue).await?;
Ok((client, Events { rx }))
}
struct Queue {
tx: Sender,
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
waiting: VecDeque<Incoming>,
}
impl Queue {
#[cfg(not(target_arch = "wasm32"))]
fn push(&mut self, item: Incoming) {
if !self.waiting.is_empty() {
self.waiting.push_back(item);
return;
}
match self.tx.try_send(item) {
Ok(()) => {}
Err(mpsc::error::TrySendError::Full(item)) => self.waiting.push_back(item),
Err(mpsc::error::TrySendError::Closed(_)) => {}
}
}
#[cfg(target_arch = "wasm32")]
fn push(&mut self, item: Incoming) {
let _ = self.tx.send(item);
}
}
impl Handler for Queue {
fn message(&mut self, message: &Message<'_>) {
self.push(Incoming::Message(message.to_owned()));
}
fn event(&mut self, event: Event) {
self.push(Incoming::Event(event));
}
fn binary(&mut self, data: &[u8]) {
self.push(Incoming::Binary(bytes::Bytes::copy_from_slice(data)));
}
#[cfg(not(target_arch = "wasm32"))]
async fn ready(&mut self) {
while !self.waiting.is_empty() {
let Ok(permit) = self.tx.reserve().await else {
self.waiting.clear();
return;
};
if let Some(item) = self.waiting.pop_front() {
permit.send(item);
}
}
}
}