389 lines
12 KiB
Rust
Raw Normal View History

2021-11-27 19:19:41 +08:00
#![allow(clippy::type_complexity)]
2021-09-19 23:21:10 +08:00
use crate::{
2021-09-30 17:24:02 +08:00
connect::{WsConnectionFuture, WsStream},
2021-09-19 23:21:10 +08:00
errors::WsError,
WsMessage,
WsModule,
2021-09-19 23:21:10 +08:00
};
2021-11-20 08:35:04 +08:00
use backend_service::errors::ServerError;
2021-09-24 16:02:17 +08:00
use bytes::Bytes;
2021-09-30 17:24:02 +08:00
use dashmap::DashMap;
2021-09-16 18:31:25 +08:00
use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender};
use futures_core::{ready, Stream};
use lib_infra::retry::{Action, FixedInterval, Retry};
2021-09-30 17:24:02 +08:00
use parking_lot::RwLock;
2021-09-16 18:31:25 +08:00
use pin_project::pin_project;
use std::{
convert::TryFrom,
fmt::Formatter,
2021-09-16 18:31:25 +08:00
future::Future,
pin::Pin,
sync::Arc,
task::{Context, Poll},
2021-10-05 17:54:11 +08:00
time::Duration,
2021-09-16 18:31:25 +08:00
};
use tokio::sync::{broadcast, oneshot};
2021-09-19 23:21:10 +08:00
use tokio_tungstenite::tungstenite::{
protocol::{frame::coding::CloseCode, CloseFrame},
Message,
2021-09-19 18:39:56 +08:00
};
2021-09-16 23:07:15 +08:00
2021-09-16 18:31:25 +08:00
pub type MsgReceiver = UnboundedReceiver<Message>;
pub type MsgSender = UnboundedSender<Message>;
2021-09-30 17:24:02 +08:00
type Handlers = DashMap<WsModule, Arc<dyn WsMessageHandler>>;
2021-09-16 18:31:25 +08:00
pub trait WsMessageHandler: Sync + Send + 'static {
fn source(&self) -> WsModule;
2021-09-18 22:32:00 +08:00
fn receive_message(&self, msg: WsMessage);
2021-09-16 18:31:25 +08:00
}
pub struct WsController {
2021-09-30 17:24:02 +08:00
handlers: Handlers,
2021-12-05 14:04:25 +08:00
state_notify: Arc<broadcast::Sender<WsConnectState>>,
sender_ctrl: Arc<RwLock<WsSenderController>>,
2021-10-05 17:54:11 +08:00
addr: Arc<RwLock<Option<String>>>,
2021-09-16 18:31:25 +08:00
}
2021-11-27 19:19:41 +08:00
impl std::default::Default for WsController {
fn default() -> Self {
2021-09-30 17:24:02 +08:00
let (state_notify, _) = broadcast::channel(16);
2021-11-27 19:19:41 +08:00
Self {
2021-09-30 17:24:02 +08:00
handlers: DashMap::new(),
2021-12-05 14:04:25 +08:00
sender_ctrl: Arc::new(RwLock::new(WsSenderController::default())),
2021-09-30 17:24:02 +08:00
state_notify: Arc::new(state_notify),
2021-10-05 17:54:11 +08:00
addr: Arc::new(RwLock::new(None)),
2021-11-27 19:19:41 +08:00
}
2021-09-16 18:31:25 +08:00
}
2021-11-27 19:19:41 +08:00
}
impl WsController {
pub fn new() -> Self { WsController::default() }
2021-09-16 18:31:25 +08:00
2021-09-30 17:24:02 +08:00
pub fn add_handler(&self, handler: Arc<dyn WsMessageHandler>) -> Result<(), WsError> {
2021-09-18 22:32:00 +08:00
let source = handler.source();
if self.handlers.contains_key(&source) {
2021-09-23 17:50:28 +08:00
log::error!("WsSource's {:?} is already registered", source);
2021-09-18 22:32:00 +08:00
}
self.handlers.insert(source, handler);
2021-09-17 19:03:46 +08:00
Ok(())
2021-09-16 23:07:15 +08:00
}
2021-10-05 17:54:11 +08:00
pub async fn start_connect(&self, addr: String) -> Result<(), ServerError> {
*self.addr.write() = Some(addr.clone());
2021-10-05 19:32:58 +08:00
let strategy = FixedInterval::from_millis(5000).take(3);
2021-10-05 17:54:11 +08:00
self.connect(addr, strategy).await
}
async fn connect<T, I>(&self, addr: String, strategy: T) -> Result<(), ServerError>
where
T: IntoIterator<IntoIter = I, Item = Duration>,
I: Iterator<Item = Duration> + Send + 'static,
{
2021-09-30 17:24:02 +08:00
let (ret, rx) = oneshot::channel::<Result<(), ServerError>>();
2021-10-05 17:54:11 +08:00
*self.addr.write() = Some(addr.clone());
let action = WsConnectAction {
addr,
handlers: self.handlers.clone(),
};
2021-10-05 17:54:11 +08:00
let retry = Retry::spawn(strategy, action);
2021-12-05 14:04:25 +08:00
let sender_ctrl = self.sender_ctrl.clone();
sender_ctrl.write().set_state(WsConnectState::Connecting);
2021-09-30 17:24:02 +08:00
tokio::spawn(async move {
match retry.await {
Ok(result) => {
let WsConnectResult {
stream,
handlers_fut,
sender,
} = result;
2021-12-05 14:04:25 +08:00
sender_ctrl.write().set_sender(sender);
sender_ctrl.write().set_state(WsConnectState::Connected);
let _ = ret.send(Ok(()));
2021-12-05 14:04:25 +08:00
spawn_stream_and_handlers(stream, handlers_fut, sender_ctrl.clone()).await;
2021-09-19 16:11:02 +08:00
},
2021-09-19 18:39:56 +08:00
Err(e) => {
2021-12-05 14:04:25 +08:00
sender_ctrl.write().set_error(e.clone());
let _ = ret.send(Err(ServerError::internal().context(e)));
2021-09-18 22:32:00 +08:00
},
2021-09-19 16:11:02 +08:00
}
2021-09-30 17:24:02 +08:00
});
rx.await?
2021-09-18 22:32:00 +08:00
}
2021-12-05 14:04:25 +08:00
pub async fn retry(&self, count: usize) -> Result<(), ServerError> {
if self.sender_ctrl.read().is_connecting() {
return Ok(());
}
let strategy = FixedInterval::from_millis(5000).take(count);
2021-10-05 17:54:11 +08:00
let addr = self
.addr
.read()
.as_ref()
.expect("must call start_connect first")
.clone();
2021-12-05 14:04:25 +08:00
2021-10-05 17:54:11 +08:00
self.connect(addr, strategy).await
}
2021-12-05 14:04:25 +08:00
pub fn state_subscribe(&self) -> broadcast::Receiver<WsConnectState> { self.state_notify.subscribe() }
pub fn sender(&self) -> Result<Arc<WsSender>, WsError> {
2021-12-05 14:04:25 +08:00
match self.sender_ctrl.read().sender() {
None => Err(WsError::internal().context("WsSender is not initialized, should call connect first")),
2021-12-05 14:04:25 +08:00
Some(sender) => Ok(sender),
}
2021-09-16 18:31:25 +08:00
}
}
async fn spawn_stream_and_handlers(
2021-09-30 17:24:02 +08:00
stream: WsStream,
handlers: WsHandlerFuture,
2021-12-05 14:04:25 +08:00
sender_ctrl: Arc<RwLock<WsSenderController>>,
2021-09-30 17:24:02 +08:00
) {
tokio::select! {
result = stream => {
2021-12-05 14:04:25 +08:00
if let Err(e) = result {
sender_ctrl.write().set_error(e);
2021-09-30 17:24:02 +08:00
}
},
2021-11-03 15:37:38 +08:00
result = handlers => tracing::debug!("handlers completed {:?}", result),
2021-09-30 17:24:02 +08:00
};
}
2021-09-16 18:31:25 +08:00
#[pin_project]
2021-09-20 15:38:55 +08:00
pub struct WsHandlerFuture {
2021-09-16 18:31:25 +08:00
#[pin]
msg_rx: MsgReceiver,
2021-09-30 17:24:02 +08:00
// Opti: Hashmap would be better
handlers: Handlers,
2021-09-16 18:31:25 +08:00
}
2021-09-20 15:38:55 +08:00
impl WsHandlerFuture {
2021-09-30 17:24:02 +08:00
fn new(handlers: Handlers, msg_rx: MsgReceiver) -> Self { Self { msg_rx, handlers } }
2021-09-24 16:02:17 +08:00
fn handler_ws_message(&self, message: Message) {
2021-11-27 19:19:41 +08:00
if let Message::Binary(bytes) = message {
self.handle_binary_message(bytes)
2021-09-24 16:02:17 +08:00
}
}
fn handle_binary_message(&self, bytes: Vec<u8>) {
let bytes = Bytes::from(bytes);
match WsMessage::try_from(bytes) {
Ok(message) => match self.handlers.get(&message.module) {
None => log::error!("Can't find any handler for message: {:?}", message),
Some(handler) => handler.receive_message(message.clone()),
},
Err(e) => {
log::error!("Deserialize binary ws message failed: {:?}", e);
},
}
}
2021-09-16 18:31:25 +08:00
}
2021-09-20 15:38:55 +08:00
impl Future for WsHandlerFuture {
2021-09-16 18:31:25 +08:00
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
loop {
match ready!(self.as_mut().project().msg_rx.poll_next(cx)) {
2021-09-18 22:32:00 +08:00
None => {
2021-09-19 16:11:02 +08:00
return Poll::Ready(());
2021-09-16 23:07:15 +08:00
},
2021-09-24 16:02:17 +08:00
Some(message) => self.handler_ws_message(message),
2021-09-16 23:07:15 +08:00
}
}
}
}
2021-09-19 18:39:56 +08:00
#[derive(Debug, Clone)]
pub struct WsSender {
2021-09-16 23:07:15 +08:00
ws_tx: MsgSender,
}
impl WsSender {
2021-09-19 18:39:56 +08:00
pub fn send_msg<T: Into<WsMessage>>(&self, msg: T) -> Result<(), WsError> {
let msg = msg.into();
2021-09-27 23:23:23 +08:00
let _ = self
.ws_tx
.unbounded_send(msg.into())
.map_err(|e| WsError::internal().context(e))?;
2021-09-16 23:07:15 +08:00
Ok(())
}
2021-09-19 18:39:56 +08:00
pub fn send_text(&self, source: &WsModule, text: &str) -> Result<(), WsError> {
2021-09-19 18:39:56 +08:00
let msg = WsMessage {
module: source.clone(),
2021-09-19 18:39:56 +08:00
data: text.as_bytes().to_vec(),
};
self.send_msg(msg)
}
pub fn send_binary(&self, source: &WsModule, bytes: Vec<u8>) -> Result<(), WsError> {
let msg = WsMessage {
module: source.clone(),
data: bytes,
};
2021-09-19 18:39:56 +08:00
self.send_msg(msg)
}
pub fn send_disconnect(&self, reason: &str) -> Result<(), WsError> {
let frame = CloseFrame {
code: CloseCode::Normal,
reason: reason.to_owned().into(),
};
let msg = Message::Close(Some(frame));
2021-09-27 23:23:23 +08:00
let _ = self
.ws_tx
.unbounded_send(msg)
.map_err(|e| WsError::internal().context(e))?;
2021-09-19 18:39:56 +08:00
Ok(())
}
2021-09-16 23:07:15 +08:00
}
struct WsConnectAction {
addr: String,
handlers: Handlers,
}
2021-12-05 14:04:25 +08:00
impl Action for WsConnectAction {
type Future = Pin<Box<dyn Future<Output = Result<Self::Item, Self::Error>> + Send + Sync>>;
type Item = WsConnectResult;
type Error = WsError;
fn run(&mut self) -> Self::Future {
let addr = self.addr.clone();
let handlers = self.handlers.clone();
Box::pin(WsConnectActionFut::new(addr, handlers))
}
}
struct WsConnectResult {
stream: WsStream,
handlers_fut: WsHandlerFuture,
sender: WsSender,
}
#[pin_project]
struct WsConnectActionFut {
addr: String,
#[pin]
conn: WsConnectionFuture,
handlers_fut: Option<WsHandlerFuture>,
sender: Option<WsSender>,
}
impl WsConnectActionFut {
fn new(addr: String, handlers: Handlers) -> Self {
// Stream User
// ┌───────────────┐ ┌──────────────┐
// ┌──────┐ │ ┌─────────┐ │ ┌────────┐ │ ┌────────┐ │
// │Server│──────┼─▶│ ws_read │──┼───▶│ msg_tx │───┼─▶│ msg_rx │ │
// └──────┘ │ └─────────┘ │ └────────┘ │ └────────┘ │
// ▲ │ │ │ │
// │ │ ┌─────────┐ │ ┌────────┐ │ ┌────────┐ │
// └─────────┼──│ws_write │◀─┼────│ ws_rx │◀──┼──│ ws_tx │ │
// │ └─────────┘ │ └────────┘ │ └────────┘ │
// └───────────────┘ └──────────────┘
let (msg_tx, msg_rx) = futures_channel::mpsc::unbounded();
let (ws_tx, ws_rx) = futures_channel::mpsc::unbounded();
let sender = WsSender { ws_tx };
let handlers_fut = WsHandlerFuture::new(handlers, msg_rx);
let conn = WsConnectionFuture::new(msg_tx, ws_rx, addr.clone());
Self {
addr,
conn,
handlers_fut: Some(handlers_fut),
sender: Some(sender),
}
}
}
impl Future for WsConnectActionFut {
type Output = Result<WsConnectResult, WsError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
match ready!(this.conn.as_mut().poll(cx)) {
Ok(stream) => {
let handlers_fut = this.handlers_fut.take().expect("Only take once");
let sender = this.sender.take().expect("Only take once");
Poll::Ready(Ok(WsConnectResult {
stream,
handlers_fut,
sender,
}))
},
2021-10-05 19:32:58 +08:00
Err(e) => Poll::Ready(Err(e)),
}
}
}
2021-12-05 14:04:25 +08:00
#[derive(Clone, Eq, PartialEq)]
pub enum WsConnectState {
Init,
Connecting,
Connected,
Disconnected,
}
2021-12-05 14:04:25 +08:00
impl std::fmt::Display for WsConnectState {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
WsConnectState::Init => f.write_str("Init"),
WsConnectState::Connected => f.write_str("Connecting"),
WsConnectState::Connecting => f.write_str("Connected"),
WsConnectState::Disconnected => f.write_str("Disconnected"),
}
}
}
impl std::fmt::Debug for WsConnectState {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(&format!("{}", self)) }
}
struct WsSenderController {
state: WsConnectState,
state_notify: Arc<broadcast::Sender<WsConnectState>>,
sender: Option<Arc<WsSender>>,
}
impl WsSenderController {
fn set_sender(&mut self, sender: WsSender) { self.sender = Some(Arc::new(sender)); }
fn set_state(&mut self, state: WsConnectState) {
if state != WsConnectState::Connected {
self.sender = None;
}
self.state = state.clone();
let _ = self.state_notify.send(state);
}
fn set_error(&mut self, error: WsError) {
log::error!("{:?}", error);
self.set_state(WsConnectState::Disconnected);
}
fn sender(&self) -> Option<Arc<WsSender>> { self.sender.clone() }
fn is_connecting(&self) -> bool { self.state == WsConnectState::Connecting }
#[allow(dead_code)]
fn is_connected(&self) -> bool { self.state == WsConnectState::Connected }
}
impl std::default::Default for WsSenderController {
fn default() -> Self {
let (state_notify, _) = broadcast::channel(16);
WsSenderController {
state: WsConnectState::Init,
state_notify: Arc::new(state_notify),
sender: None,
}
}
}