ws_manager.rs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. use async_stream::stream;
  2. use bytes::Bytes;
  3. use flowy_collaboration::entities::{
  4. revision::{RevId, RevisionRange},
  5. ws_data::{ClientRevisionWSData, NewDocumentUser, ServerRevisionWSData, ServerRevisionWSDataType},
  6. };
  7. use flowy_error::{internal_error, FlowyError, FlowyResult};
  8. use futures_util::stream::StreamExt;
  9. use lib_infra::future::FutureResult;
  10. use lib_ws::WSConnectState;
  11. use std::{convert::TryFrom, sync::Arc};
  12. use tokio::{
  13. sync::{
  14. broadcast,
  15. mpsc,
  16. mpsc::{Receiver, Sender},
  17. },
  18. task::spawn_blocking,
  19. time::{interval, Duration},
  20. };
  21. // The consumer consumes the messages pushed by the web socket.
  22. pub trait RevisionWSSteamConsumer: Send + Sync {
  23. fn receive_push_revision(&self, bytes: Bytes) -> FutureResult<(), FlowyError>;
  24. fn receive_ack(&self, id: String, ty: ServerRevisionWSDataType) -> FutureResult<(), FlowyError>;
  25. fn receive_new_user_connect(&self, new_user: NewDocumentUser) -> FutureResult<(), FlowyError>;
  26. fn pull_revisions_in_range(&self, range: RevisionRange) -> FutureResult<(), FlowyError>;
  27. }
  28. // The sink provides the data that will be sent through the web socket to the
  29. // backend.
  30. pub trait RevisionWSSinkDataProvider: Send + Sync {
  31. fn next(&self) -> FutureResult<Option<ClientRevisionWSData>, FlowyError>;
  32. }
  33. pub type WSStateReceiver = tokio::sync::broadcast::Receiver<WSConnectState>;
  34. pub trait RevisionWebSocket: Send + Sync {
  35. fn send(&self, data: ClientRevisionWSData) -> Result<(), FlowyError>;
  36. fn subscribe_state_changed(&self) -> WSStateReceiver;
  37. }
  38. pub struct RevisionWebSocketManager {
  39. pub object_id: String,
  40. data_provider: Arc<dyn RevisionWSSinkDataProvider>,
  41. stream_consumer: Arc<dyn RevisionWSSteamConsumer>,
  42. web_socket: Arc<dyn RevisionWebSocket>,
  43. pub ws_passthrough_tx: Sender<ServerRevisionWSData>,
  44. ws_passthrough_rx: Option<Receiver<ServerRevisionWSData>>,
  45. pub state_passthrough_tx: broadcast::Sender<WSConnectState>,
  46. stop_sync_tx: SinkStopTx,
  47. }
  48. impl RevisionWebSocketManager {
  49. pub fn new(
  50. object_id: &str,
  51. web_socket: Arc<dyn RevisionWebSocket>,
  52. data_provider: Arc<dyn RevisionWSSinkDataProvider>,
  53. stream_consumer: Arc<dyn RevisionWSSteamConsumer>,
  54. ping_duration: Duration,
  55. ) -> Self {
  56. let (ws_passthrough_tx, ws_passthrough_rx) = mpsc::channel(1000);
  57. let (stop_sync_tx, _) = tokio::sync::broadcast::channel(2);
  58. let object_id = object_id.to_string();
  59. let (state_passthrough_tx, _) = broadcast::channel(2);
  60. let mut manager = RevisionWebSocketManager {
  61. object_id,
  62. data_provider,
  63. stream_consumer,
  64. web_socket,
  65. ws_passthrough_tx,
  66. ws_passthrough_rx: Some(ws_passthrough_rx),
  67. state_passthrough_tx,
  68. stop_sync_tx,
  69. };
  70. manager.run(ping_duration);
  71. manager
  72. }
  73. fn run(&mut self, ping_duration: Duration) {
  74. let ws_msg_rx = self.ws_passthrough_rx.take().expect("Only take once");
  75. let sink = RevisionWSSink::new(
  76. &self.object_id,
  77. self.data_provider.clone(),
  78. self.web_socket.clone(),
  79. self.stop_sync_tx.subscribe(),
  80. ping_duration,
  81. );
  82. let stream = RevisionWSStream::new(
  83. &self.object_id,
  84. self.stream_consumer.clone(),
  85. ws_msg_rx,
  86. self.stop_sync_tx.subscribe(),
  87. );
  88. tokio::spawn(sink.run());
  89. tokio::spawn(stream.run());
  90. }
  91. pub fn scribe_state(&self) -> broadcast::Receiver<WSConnectState> { self.state_passthrough_tx.subscribe() }
  92. pub fn stop(&self) {
  93. if self.stop_sync_tx.send(()).is_ok() {
  94. tracing::trace!("{} stop sync", self.object_id)
  95. }
  96. }
  97. }
  98. impl std::ops::Drop for RevisionWebSocketManager {
  99. fn drop(&mut self) { tracing::trace!("{} RevisionWebSocketManager was dropped", self.object_id) }
  100. }
  101. pub struct RevisionWSStream {
  102. object_id: String,
  103. consumer: Arc<dyn RevisionWSSteamConsumer>,
  104. ws_msg_rx: Option<mpsc::Receiver<ServerRevisionWSData>>,
  105. stop_rx: Option<SinkStopRx>,
  106. }
  107. impl std::ops::Drop for RevisionWSStream {
  108. fn drop(&mut self) { tracing::trace!("{} RevisionWSStream was dropped", self.object_id) }
  109. }
  110. impl RevisionWSStream {
  111. pub fn new(
  112. object_id: &str,
  113. consumer: Arc<dyn RevisionWSSteamConsumer>,
  114. ws_msg_rx: mpsc::Receiver<ServerRevisionWSData>,
  115. stop_rx: SinkStopRx,
  116. ) -> Self {
  117. RevisionWSStream {
  118. object_id: object_id.to_owned(),
  119. consumer,
  120. ws_msg_rx: Some(ws_msg_rx),
  121. stop_rx: Some(stop_rx),
  122. }
  123. }
  124. pub async fn run(mut self) {
  125. let mut receiver = self.ws_msg_rx.take().expect("Only take once");
  126. let mut stop_rx = self.stop_rx.take().expect("Only take once");
  127. let object_id = self.object_id.clone();
  128. let stream = stream! {
  129. loop {
  130. tokio::select! {
  131. result = receiver.recv() => {
  132. match result {
  133. Some(msg) => {
  134. yield msg
  135. },
  136. None => {
  137. tracing::debug!("[RevisionWSStream:{}] loop exit", object_id);
  138. break;
  139. },
  140. }
  141. },
  142. _ = stop_rx.recv() => {
  143. tracing::debug!("[RevisionWSStream:{}] loop exit", object_id);
  144. break
  145. },
  146. };
  147. }
  148. };
  149. stream
  150. .for_each(|msg| async {
  151. match self.handle_message(msg).await {
  152. Ok(_) => {},
  153. Err(e) => tracing::error!("[RevisionWSStream:{}] error: {}", self.object_id, e),
  154. }
  155. })
  156. .await;
  157. }
  158. async fn handle_message(&self, msg: ServerRevisionWSData) -> FlowyResult<()> {
  159. let ServerRevisionWSData { object_id: _, ty, data } = msg;
  160. let bytes = spawn_blocking(move || Bytes::from(data))
  161. .await
  162. .map_err(internal_error)?;
  163. tracing::trace!("[RevisionWSStream]: new message: {:?}", ty);
  164. match ty {
  165. ServerRevisionWSDataType::ServerPushRev => {
  166. let _ = self.consumer.receive_push_revision(bytes).await?;
  167. },
  168. ServerRevisionWSDataType::ServerPullRev => {
  169. let range = RevisionRange::try_from(bytes)?;
  170. let _ = self.consumer.pull_revisions_in_range(range).await?;
  171. },
  172. ServerRevisionWSDataType::ServerAck => {
  173. let rev_id = RevId::try_from(bytes).unwrap().value;
  174. let _ = self.consumer.receive_ack(rev_id.to_string(), ty).await;
  175. },
  176. ServerRevisionWSDataType::UserConnect => {
  177. let new_user = NewDocumentUser::try_from(bytes)?;
  178. let _ = self.consumer.receive_new_user_connect(new_user).await;
  179. },
  180. }
  181. Ok(())
  182. }
  183. }
  184. type SinkStopRx = broadcast::Receiver<()>;
  185. type SinkStopTx = broadcast::Sender<()>;
  186. pub struct RevisionWSSink {
  187. provider: Arc<dyn RevisionWSSinkDataProvider>,
  188. ws_sender: Arc<dyn RevisionWebSocket>,
  189. stop_rx: Option<SinkStopRx>,
  190. object_id: String,
  191. ping_duration: Duration,
  192. }
  193. impl RevisionWSSink {
  194. pub fn new(
  195. object_id: &str,
  196. provider: Arc<dyn RevisionWSSinkDataProvider>,
  197. ws_sender: Arc<dyn RevisionWebSocket>,
  198. stop_rx: SinkStopRx,
  199. ping_duration: Duration,
  200. ) -> Self {
  201. Self {
  202. provider,
  203. ws_sender,
  204. stop_rx: Some(stop_rx),
  205. object_id: object_id.to_owned(),
  206. ping_duration,
  207. }
  208. }
  209. pub async fn run(mut self) {
  210. let (tx, mut rx) = mpsc::channel(1);
  211. let mut stop_rx = self.stop_rx.take().expect("Only take once");
  212. let object_id = self.object_id.clone();
  213. tokio::spawn(tick(tx, self.ping_duration));
  214. let stream = stream! {
  215. loop {
  216. tokio::select! {
  217. result = rx.recv() => {
  218. match result {
  219. Some(msg) => yield msg,
  220. None => break,
  221. }
  222. },
  223. _ = stop_rx.recv() => {
  224. tracing::trace!("[RevisionWSSink:{}] loop exit", object_id);
  225. break
  226. },
  227. };
  228. }
  229. };
  230. stream
  231. .for_each(|_| async {
  232. match self.send_next_revision().await {
  233. Ok(_) => {},
  234. Err(e) => tracing::error!("[RevisionWSSink] send failed, {:?}", e),
  235. }
  236. })
  237. .await;
  238. }
  239. async fn send_next_revision(&self) -> FlowyResult<()> {
  240. match self.provider.next().await? {
  241. None => {
  242. tracing::trace!("Finish synchronizing revisions");
  243. Ok(())
  244. },
  245. Some(data) => {
  246. tracing::trace!("[RevisionWSSink] send: {}:{}-{:?}", data.object_id, data.id(), data.ty);
  247. self.ws_sender.send(data)
  248. },
  249. }
  250. }
  251. }
  252. impl std::ops::Drop for RevisionWSSink {
  253. fn drop(&mut self) { tracing::trace!("{} RevisionWSSink was dropped", self.object_id) }
  254. }
  255. async fn tick(sender: mpsc::Sender<()>, duration: Duration) {
  256. let mut interval = interval(duration);
  257. while sender.send(()).await.is_ok() {
  258. interval.tick().await;
  259. }
  260. }