use crate::client::{
Scheduler, SocketConnection, SocketEvents, SocketFactory, SocketMessage, Timer, timer_delay,
};
use futures_util::{SinkExt, StreamExt};
use std::rc::Rc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::mpsc;
use tokio::task::{AbortHandle, spawn_local};
use tokio::time::{Instant, MissedTickBehavior};
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
use tokio_tungstenite::tungstenite::protocol::{CloseFrame, WebSocketConfig};
use tokio_tungstenite::tungstenite::{self, Message};
pub struct TokioScheduler {
start: Instant,
}
impl TokioScheduler {
pub fn new() -> Self {
TokioScheduler {
start: Instant::now(),
}
}
}
impl Default for TokioScheduler {
fn default() -> Self {
Self::new()
}
}
fn delay(ms: f64) -> Duration {
Duration::from_secs_f64(timer_delay(ms) / 1000.0)
}
struct TokioTimer(AbortHandle);
impl Timer for TokioTimer {
fn cancel(&self) {
self.0.abort();
}
}
impl Scheduler for TokioScheduler {
fn now(&self) -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0.0, |d| d.as_millis() as f64)
}
fn monotonic_now(&self) -> f64 {
self.start.elapsed().as_secs_f64() * 1000.0
}
fn schedule(&self, ms: f64, action: Box<dyn FnOnce()>) -> Box<dyn Timer> {
let d = delay(ms);
let task = spawn_local(async move {
tokio::time::sleep(d).await;
action();
});
Box::new(TokioTimer(task.abort_handle()))
}
fn schedule_repeating(&self, ms: f64, mut action: Box<dyn FnMut()>) -> Box<dyn Timer> {
let period = delay(ms).max(Duration::from_millis(1));
let task = spawn_local(async move {
let mut interval = tokio::time::interval_at(Instant::now() + period, period);
interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
loop {
interval.tick().await;
action();
}
});
Box::new(TokioTimer(task.abort_handle()))
}
fn checkpoint(&self, action: Box<dyn FnOnce()>) {
spawn_local(async move { action() });
}
}
#[derive(Default)]
pub struct TokioSocketFactory {
_private: (),
}
impl TokioSocketFactory {
pub fn new() -> Self {
Self::default()
}
}
enum Command {
Send(String),
Close(Option<u16>),
}
struct TokioSocket {
commands: mpsc::UnboundedSender<Command>,
}
impl SocketConnection for TokioSocket {
fn send(&self, text: &str) {
let _ = self.commands.send(Command::Send(text.to_owned()));
}
fn close(&self, code: Option<u16>) {
let _ = self.commands.send(Command::Close(code));
}
}
impl SocketFactory for TokioSocketFactory {
fn open(
&self,
url: &str,
sec_protocol: Option<&str>,
events: Rc<dyn SocketEvents>,
) -> Box<dyn SocketConnection> {
let (commands, receiver) = mpsc::unbounded_channel();
let url = url.to_owned();
let sec_protocol = sec_protocol.map(str::to_owned);
spawn_local(run_socket(url, sec_protocol, events, receiver));
Box::new(TokioSocket { commands })
}
}
const ABNORMAL_CLOSURE: u16 = 1006;
const MAX_MESSAGE_SIZE: usize = 64 << 20;
async fn run_socket(
url: String,
sec_protocol: Option<String>,
events: Rc<dyn SocketEvents>,
mut commands: mpsc::UnboundedReceiver<Command>,
) {
let request = (|| -> Result<_, tungstenite::Error> {
let mut request = url.as_str().into_client_request()?;
if let Some(p) = &sec_protocol {
let value = HeaderValue::from_str(p).map_err(tungstenite::http::Error::from)?;
request
.headers_mut()
.insert("Sec-WebSocket-Protocol", value);
}
Ok(request)
})();
let connected = match request {
Ok(request) => {
tokio::select! {
r = tokio_tungstenite::connect_async_with_config(request, Some(config()), false) => {
r.map(|(ws, _)| ws)
}
_ = commands.recv() => return,
}
}
Err(e) => Err(e),
};
let mut ws = match connected {
Ok(ws) => ws,
Err(e) => {
events.did_close(ABNORMAL_CLOSURE, &e.to_string(), false);
return;
}
};
events.did_open();
loop {
tokio::select! {
command = commands.recv() => match command {
Some(Command::Send(text)) => {
let _ = ws.send(Message::text(text)).await;
}
Some(Command::Close(code)) => {
let _ = ws.close(close_frame(code)).await;
return;
}
None => {
let _ = ws.close(None).await;
return;
}
},
message = ws.next() => match message {
Some(Ok(Message::Text(text))) => {
events.did_receive(SocketMessage::Text(text.as_str().to_owned()));
}
Some(Ok(Message::Binary(bytes))) => {
events.did_receive(SocketMessage::Binary(bytes.to_vec()));
}
Some(Ok(Message::Close(frame))) => {
let (code, reason) = frame.map_or((1005, String::new()), |f| {
(u16::from(f.code), f.reason.as_str().to_owned())
});
events.did_close(code, &reason, true);
return;
}
Some(Ok(_)) => {}
Some(Err(e)) => {
events.did_close(ABNORMAL_CLOSURE, &e.to_string(), false);
return;
}
None => {
events.did_close(ABNORMAL_CLOSURE, "", false);
return;
}
},
}
}
}
fn config() -> WebSocketConfig {
WebSocketConfig::default()
.max_frame_size(Some(MAX_MESSAGE_SIZE))
.max_message_size(Some(MAX_MESSAGE_SIZE))
}
fn close_frame(code: Option<u16>) -> Option<CloseFrame> {
code.map(|c| CloseFrame {
code: CloseCode::from(c),
reason: "".into(),
})
}