AppFlowy/frontend/rust-lib/flowy-sync/src/ws_manager.rs

283 lines
9.5 KiB
Rust
Raw Normal View History

2022-01-11 14:23:19 +00:00
use async_stream::stream;
2021-12-20 07:37:37 +00:00
use bytes::Bytes;
2022-01-11 14:23:19 +00:00
use flowy_collaboration::entities::{
revision::{RevId, RevisionRange},
2022-01-15 03:20:28 +00:00
ws_data::{ClientRevisionWSData, NewDocumentUser, ServerRevisionWSData, ServerRevisionWSDataType},
2021-12-20 07:37:37 +00:00
};
use flowy_error::{internal_error, FlowyError, FlowyResult};
2022-01-14 07:23:21 +00:00
use futures_util::stream::StreamExt;
2021-12-20 07:37:37 +00:00
use lib_infra::future::FutureResult;
use lib_ws::WSConnectState;
2022-01-11 14:23:19 +00:00
use std::{convert::TryFrom, sync::Arc};
use tokio::{
sync::{
broadcast,
mpsc,
2022-01-12 04:40:41 +00:00
mpsc::{Receiver, Sender},
2022-01-11 14:23:19 +00:00
},
task::spawn_blocking,
time::{interval, Duration},
};
2021-12-20 07:37:37 +00:00
2022-01-12 04:40:41 +00:00
// The consumer consumes the messages pushed by the web socket.
2022-01-14 07:23:21 +00:00
pub trait RevisionWSSteamConsumer: Send + Sync {
2022-01-12 04:40:41 +00:00
fn receive_push_revision(&self, bytes: Bytes) -> FutureResult<(), FlowyError>;
2022-01-14 07:23:21 +00:00
fn receive_ack(&self, id: String, ty: ServerRevisionWSDataType) -> FutureResult<(), FlowyError>;
2022-01-12 04:40:41 +00:00
fn receive_new_user_connect(&self, new_user: NewDocumentUser) -> FutureResult<(), FlowyError>;
fn pull_revisions_in_range(&self, range: RevisionRange) -> FutureResult<(), FlowyError>;
}
// The sink provides the data that will be sent through the web socket to the
// backend.
2022-01-14 07:23:21 +00:00
pub trait RevisionWSSinkDataProvider: Send + Sync {
fn next(&self) -> FutureResult<Option<ClientRevisionWSData>, FlowyError>;
}
pub type WSStateReceiver = tokio::sync::broadcast::Receiver<WSConnectState>;
pub trait RevisionWebSocket: Send + Sync {
fn send(&self, data: ClientRevisionWSData) -> Result<(), FlowyError>;
fn subscribe_state_changed(&self) -> WSStateReceiver;
2022-01-12 04:40:41 +00:00
}
2022-01-14 07:23:21 +00:00
pub struct RevisionWebSocketManager {
pub object_id: String,
data_provider: Arc<dyn RevisionWSSinkDataProvider>,
stream_consumer: Arc<dyn RevisionWSSteamConsumer>,
2022-01-14 12:52:03 +00:00
web_socket: Arc<dyn RevisionWebSocket>,
2022-01-14 07:23:21 +00:00
pub ws_passthrough_tx: Sender<ServerRevisionWSData>,
ws_passthrough_rx: Option<Receiver<ServerRevisionWSData>>,
pub state_passthrough_tx: broadcast::Sender<WSConnectState>,
2022-01-11 14:23:19 +00:00
stop_sync_tx: SinkStopTx,
2021-12-20 07:37:37 +00:00
}
2022-01-14 07:23:21 +00:00
impl RevisionWebSocketManager {
pub fn new(
object_id: &str,
2022-01-14 12:52:03 +00:00
web_socket: Arc<dyn RevisionWebSocket>,
2022-01-14 07:23:21 +00:00
data_provider: Arc<dyn RevisionWSSinkDataProvider>,
stream_consumer: Arc<dyn RevisionWSSteamConsumer>,
ping_duration: Duration,
2022-01-11 14:23:19 +00:00
) -> Self {
2022-01-12 04:40:41 +00:00
let (ws_passthrough_tx, ws_passthrough_rx) = mpsc::channel(1000);
2022-01-11 14:23:19 +00:00
let (stop_sync_tx, _) = tokio::sync::broadcast::channel(2);
2022-01-14 07:23:21 +00:00
let object_id = object_id.to_string();
2022-01-12 04:40:41 +00:00
let (state_passthrough_tx, _) = broadcast::channel(2);
2022-01-14 07:23:21 +00:00
let mut manager = RevisionWebSocketManager {
object_id,
2022-01-11 14:23:19 +00:00
data_provider,
stream_consumer,
2022-01-14 12:52:03 +00:00
web_socket,
2022-01-12 04:40:41 +00:00
ws_passthrough_tx,
ws_passthrough_rx: Some(ws_passthrough_rx),
state_passthrough_tx,
2022-01-11 14:23:19 +00:00
stop_sync_tx,
};
2022-01-14 07:23:21 +00:00
manager.run(ping_duration);
2022-01-11 14:23:19 +00:00
manager
}
2021-12-20 07:37:37 +00:00
2022-01-14 07:23:21 +00:00
fn run(&mut self, ping_duration: Duration) {
2022-01-12 04:40:41 +00:00
let ws_msg_rx = self.ws_passthrough_rx.take().expect("Only take once");
2022-01-14 07:23:21 +00:00
let sink = RevisionWSSink::new(
&self.object_id,
2022-01-11 14:23:19 +00:00
self.data_provider.clone(),
2022-01-14 12:52:03 +00:00
self.web_socket.clone(),
2022-01-11 14:23:19 +00:00
self.stop_sync_tx.subscribe(),
2022-01-14 07:23:21 +00:00
ping_duration,
2022-01-11 14:23:19 +00:00
);
2022-01-14 07:23:21 +00:00
let stream = RevisionWSStream::new(
&self.object_id,
2022-01-11 14:23:19 +00:00
self.stream_consumer.clone(),
ws_msg_rx,
self.stop_sync_tx.subscribe(),
);
tokio::spawn(sink.run());
tokio::spawn(stream.run());
2021-12-20 07:37:37 +00:00
}
2022-01-12 04:40:41 +00:00
pub fn scribe_state(&self) -> broadcast::Receiver<WSConnectState> { self.state_passthrough_tx.subscribe() }
2022-01-11 14:23:19 +00:00
2022-01-14 07:23:21 +00:00
pub fn stop(&self) {
2022-01-11 14:23:19 +00:00
if self.stop_sync_tx.send(()).is_ok() {
2022-01-14 07:23:21 +00:00
tracing::trace!("{} stop sync", self.object_id)
2022-01-11 14:23:19 +00:00
}
2021-12-20 07:37:37 +00:00
}
}
2022-01-14 07:23:21 +00:00
impl std::ops::Drop for RevisionWebSocketManager {
fn drop(&mut self) { tracing::trace!("{} RevisionWebSocketManager was dropped", self.object_id) }
2022-01-02 02:34:42 +00:00
}
2022-01-14 07:23:21 +00:00
pub struct RevisionWSStream {
object_id: String,
consumer: Arc<dyn RevisionWSSteamConsumer>,
ws_msg_rx: Option<mpsc::Receiver<ServerRevisionWSData>>,
2022-01-11 14:23:19 +00:00
stop_rx: Option<SinkStopRx>,
}
2022-01-02 02:34:42 +00:00
2022-01-14 07:23:21 +00:00
impl std::ops::Drop for RevisionWSStream {
fn drop(&mut self) { tracing::trace!("{} RevisionWSStream was dropped", self.object_id) }
2022-01-12 09:08:50 +00:00
}
2022-01-14 07:23:21 +00:00
impl RevisionWSStream {
2022-01-11 14:23:19 +00:00
pub fn new(
2022-01-14 07:23:21 +00:00
object_id: &str,
consumer: Arc<dyn RevisionWSSteamConsumer>,
ws_msg_rx: mpsc::Receiver<ServerRevisionWSData>,
2022-01-11 14:23:19 +00:00
stop_rx: SinkStopRx,
) -> Self {
2022-01-14 07:23:21 +00:00
RevisionWSStream {
object_id: object_id.to_owned(),
2022-01-11 14:23:19 +00:00
consumer,
ws_msg_rx: Some(ws_msg_rx),
stop_rx: Some(stop_rx),
2021-12-25 13:44:45 +00:00
}
}
2022-01-11 14:23:19 +00:00
pub async fn run(mut self) {
let mut receiver = self.ws_msg_rx.take().expect("Only take once");
let mut stop_rx = self.stop_rx.take().expect("Only take once");
2022-01-14 07:23:21 +00:00
let object_id = self.object_id.clone();
2022-01-11 14:23:19 +00:00
let stream = stream! {
loop {
tokio::select! {
result = receiver.recv() => {
match result {
Some(msg) => {
yield msg
},
None => {
2022-01-14 07:23:21 +00:00
tracing::debug!("[RevisionWSStream:{}] loop exit", object_id);
2022-01-11 14:23:19 +00:00
break;
},
}
},
_ = stop_rx.recv() => {
2022-01-14 07:23:21 +00:00
tracing::debug!("[RevisionWSStream:{}] loop exit", object_id);
2022-01-11 14:23:19 +00:00
break
},
};
}
};
2022-01-11 14:23:19 +00:00
stream
.for_each(|msg| async {
match self.handle_message(msg).await {
Ok(_) => {},
2022-01-14 07:23:21 +00:00
Err(e) => tracing::error!("[RevisionWSStream:{}] error: {}", self.object_id, e),
2022-01-11 14:23:19 +00:00
}
})
.await;
2021-12-25 13:44:45 +00:00
}
2021-12-20 07:37:37 +00:00
2022-01-14 07:23:21 +00:00
async fn handle_message(&self, msg: ServerRevisionWSData) -> FlowyResult<()> {
let ServerRevisionWSData { object_id: _, ty, data } = msg;
2022-01-11 14:23:19 +00:00
let bytes = spawn_blocking(move || Bytes::from(data))
.await
.map_err(internal_error)?;
2021-12-20 07:37:37 +00:00
2022-01-14 07:23:21 +00:00
tracing::trace!("[RevisionWSStream]: new message: {:?}", ty);
2022-01-11 14:23:19 +00:00
match ty {
2022-01-14 07:23:21 +00:00
ServerRevisionWSDataType::ServerPushRev => {
2022-01-11 14:23:19 +00:00
let _ = self.consumer.receive_push_revision(bytes).await?;
},
2022-01-14 07:23:21 +00:00
ServerRevisionWSDataType::ServerPullRev => {
2022-01-11 14:23:19 +00:00
let range = RevisionRange::try_from(bytes)?;
let _ = self.consumer.pull_revisions_in_range(range).await?;
},
2022-01-14 07:23:21 +00:00
ServerRevisionWSDataType::ServerAck => {
2022-01-11 14:23:19 +00:00
let rev_id = RevId::try_from(bytes).unwrap().value;
let _ = self.consumer.receive_ack(rev_id.to_string(), ty).await;
},
2022-01-14 07:23:21 +00:00
ServerRevisionWSDataType::UserConnect => {
2022-01-11 14:23:19 +00:00
let new_user = NewDocumentUser::try_from(bytes)?;
let _ = self.consumer.receive_new_user_connect(new_user).await;
},
2021-12-20 07:37:37 +00:00
}
2022-01-11 14:23:19 +00:00
Ok(())
2021-12-20 07:37:37 +00:00
}
2022-01-11 14:23:19 +00:00
}
2021-12-20 07:37:37 +00:00
2022-01-12 04:40:41 +00:00
type SinkStopRx = broadcast::Receiver<()>;
type SinkStopTx = broadcast::Sender<()>;
2022-01-14 07:23:21 +00:00
pub struct RevisionWSSink {
provider: Arc<dyn RevisionWSSinkDataProvider>,
ws_sender: Arc<dyn RevisionWebSocket>,
2022-01-11 14:23:19 +00:00
stop_rx: Option<SinkStopRx>,
2022-01-14 07:23:21 +00:00
object_id: String,
ping_duration: Duration,
2022-01-11 14:23:19 +00:00
}
2021-12-20 07:37:37 +00:00
2022-01-14 07:23:21 +00:00
impl RevisionWSSink {
2022-01-11 14:23:19 +00:00
pub fn new(
2022-01-14 07:23:21 +00:00
object_id: &str,
provider: Arc<dyn RevisionWSSinkDataProvider>,
ws_sender: Arc<dyn RevisionWebSocket>,
2022-01-11 14:23:19 +00:00
stop_rx: SinkStopRx,
2022-01-14 07:23:21 +00:00
ping_duration: Duration,
2022-01-11 14:23:19 +00:00
) -> Self {
Self {
provider,
ws_sender,
stop_rx: Some(stop_rx),
2022-01-14 07:23:21 +00:00
object_id: object_id.to_owned(),
ping_duration,
2021-12-20 07:37:37 +00:00
}
}
2022-01-11 14:23:19 +00:00
pub async fn run(mut self) {
2022-01-12 04:40:41 +00:00
let (tx, mut rx) = mpsc::channel(1);
2022-01-11 14:23:19 +00:00
let mut stop_rx = self.stop_rx.take().expect("Only take once");
2022-01-14 07:23:21 +00:00
let object_id = self.object_id.clone();
tokio::spawn(tick(tx, self.ping_duration));
2022-01-11 14:23:19 +00:00
let stream = stream! {
loop {
tokio::select! {
result = rx.recv() => {
match result {
Some(msg) => yield msg,
None => break,
2021-12-20 07:37:37 +00:00
}
},
2022-01-11 14:23:19 +00:00
_ = stop_rx.recv() => {
2022-01-14 07:23:21 +00:00
tracing::trace!("[RevisionWSSink:{}] loop exit", object_id);
2022-01-11 14:23:19 +00:00
break
},
2021-12-20 07:37:37 +00:00
};
2022-01-11 14:23:19 +00:00
}
};
stream
.for_each(|_| async {
match self.send_next_revision().await {
Ok(_) => {},
2022-01-14 07:23:21 +00:00
Err(e) => tracing::error!("[RevisionWSSink] send failed, {:?}", e),
2021-12-20 07:37:37 +00:00
}
2022-01-11 14:23:19 +00:00
})
.await;
}
async fn send_next_revision(&self) -> FlowyResult<()> {
match self.provider.next().await? {
None => {
tracing::trace!("Finish synchronizing revisions");
Ok(())
2021-12-20 07:37:37 +00:00
},
2022-01-11 14:23:19 +00:00
Some(data) => {
2022-01-14 07:23:21 +00:00
tracing::trace!("[RevisionWSSink] send: {}:{}-{:?}", data.object_id, data.id(), data.ty);
2022-01-11 14:23:19 +00:00
self.ws_sender.send(data)
2021-12-20 07:37:37 +00:00
},
}
2022-01-11 14:23:19 +00:00
}
}
2021-12-20 07:37:37 +00:00
2022-01-14 07:23:21 +00:00
impl std::ops::Drop for RevisionWSSink {
fn drop(&mut self) { tracing::trace!("{} RevisionWSSink was dropped", self.object_id) }
2022-01-12 09:08:50 +00:00
}
2022-01-14 07:23:21 +00:00
async fn tick(sender: mpsc::Sender<()>, duration: Duration) {
let mut interval = interval(duration);
2022-01-12 04:40:41 +00:00
while sender.send(()).await.is_ok() {
2022-01-11 14:23:19 +00:00
interval.tick().await;
2021-12-20 07:37:37 +00:00
}
}