web_socket.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. use crate::old_editor::queue::{EditorCommand, EditorCommandSender, TextTransformOperations};
  2. use crate::TEXT_BLOCK_SYNC_INTERVAL_IN_MILLIS;
  3. use bytes::Bytes;
  4. use flowy_database::ConnectionPool;
  5. use flowy_error::{internal_error, FlowyError, FlowyResult};
  6. use flowy_revision::*;
  7. use flowy_sync::entities::revision::Revision;
  8. use flowy_sync::util::make_operations_from_revisions;
  9. use flowy_sync::{
  10. entities::{
  11. revision::RevisionRange,
  12. ws_data::{ClientRevisionWSData, NewDocumentUser, ServerRevisionWSDataType},
  13. },
  14. errors::CollaborateResult,
  15. };
  16. use lib_infra::future::{BoxResultFuture, FutureResult};
  17. use lib_ot::text_delta::DeltaTextOperations;
  18. use lib_ws::WSConnectState;
  19. use std::{sync::Arc, time::Duration};
  20. use tokio::sync::{broadcast, oneshot};
  21. #[derive(Clone)]
  22. pub struct DeltaDocumentResolveOperations(pub DeltaTextOperations);
  23. impl OperationsDeserializer<DeltaDocumentResolveOperations> for DeltaDocumentResolveOperations {
  24. fn deserialize_revisions(revisions: Vec<Revision>) -> FlowyResult<DeltaDocumentResolveOperations> {
  25. Ok(DeltaDocumentResolveOperations(make_operations_from_revisions(
  26. revisions,
  27. )?))
  28. }
  29. }
  30. impl OperationsSerializer for DeltaDocumentResolveOperations {
  31. fn serialize_operations(&self) -> Bytes {
  32. self.0.json_bytes()
  33. }
  34. }
  35. impl DeltaDocumentResolveOperations {
  36. pub fn into_inner(self) -> DeltaTextOperations {
  37. self.0
  38. }
  39. }
  40. pub type DocumentConflictController = ConflictController<DeltaDocumentResolveOperations, Arc<ConnectionPool>>;
  41. #[allow(dead_code)]
  42. pub(crate) async fn make_document_ws_manager(
  43. doc_id: String,
  44. user_id: String,
  45. edit_cmd_tx: EditorCommandSender,
  46. rev_manager: Arc<RevisionManager<Arc<ConnectionPool>>>,
  47. rev_web_socket: Arc<dyn RevisionWebSocket>,
  48. ) -> Arc<RevisionWebSocketManager> {
  49. let ws_data_provider = Arc::new(WSDataProvider::new(&doc_id, Arc::new(rev_manager.clone())));
  50. let resolver = Arc::new(DocumentConflictResolver { edit_cmd_tx });
  51. let conflict_controller =
  52. DocumentConflictController::new(&user_id, resolver, Arc::new(ws_data_provider.clone()), rev_manager);
  53. let ws_data_stream = Arc::new(DocumentRevisionWSDataStream::new(conflict_controller));
  54. let ws_data_sink = Arc::new(DocumentWSDataSink(ws_data_provider));
  55. let ping_duration = Duration::from_millis(TEXT_BLOCK_SYNC_INTERVAL_IN_MILLIS);
  56. let ws_manager = Arc::new(RevisionWebSocketManager::new(
  57. "Block",
  58. &doc_id,
  59. rev_web_socket,
  60. ws_data_sink,
  61. ws_data_stream,
  62. ping_duration,
  63. ));
  64. listen_document_ws_state(&user_id, &doc_id, ws_manager.scribe_state());
  65. ws_manager
  66. }
  67. #[allow(dead_code)]
  68. fn listen_document_ws_state(_user_id: &str, _doc_id: &str, mut subscriber: broadcast::Receiver<WSConnectState>) {
  69. tokio::spawn(async move {
  70. while let Ok(state) = subscriber.recv().await {
  71. match state {
  72. WSConnectState::Init => {}
  73. WSConnectState::Connecting => {}
  74. WSConnectState::Connected => {}
  75. WSConnectState::Disconnected => {}
  76. }
  77. }
  78. });
  79. }
  80. pub(crate) struct DocumentRevisionWSDataStream {
  81. conflict_controller: Arc<DocumentConflictController>,
  82. }
  83. impl DocumentRevisionWSDataStream {
  84. #[allow(dead_code)]
  85. pub fn new(conflict_controller: DocumentConflictController) -> Self {
  86. Self {
  87. conflict_controller: Arc::new(conflict_controller),
  88. }
  89. }
  90. }
  91. impl RevisionWSDataStream for DocumentRevisionWSDataStream {
  92. fn receive_push_revision(&self, bytes: Bytes) -> BoxResultFuture<(), FlowyError> {
  93. let resolver = self.conflict_controller.clone();
  94. Box::pin(async move { resolver.receive_bytes(bytes).await })
  95. }
  96. fn receive_ack(&self, id: String, ty: ServerRevisionWSDataType) -> BoxResultFuture<(), FlowyError> {
  97. let resolver = self.conflict_controller.clone();
  98. Box::pin(async move { resolver.ack_revision(id, ty).await })
  99. }
  100. fn receive_new_user_connect(&self, _new_user: NewDocumentUser) -> BoxResultFuture<(), FlowyError> {
  101. // Do nothing by now, just a placeholder for future extension.
  102. Box::pin(async move { Ok(()) })
  103. }
  104. fn pull_revisions_in_range(&self, range: RevisionRange) -> BoxResultFuture<(), FlowyError> {
  105. let resolver = self.conflict_controller.clone();
  106. Box::pin(async move { resolver.send_revisions(range).await })
  107. }
  108. }
  109. pub(crate) struct DocumentWSDataSink(pub(crate) Arc<WSDataProvider>);
  110. impl RevisionWebSocketSink for DocumentWSDataSink {
  111. fn next(&self) -> FutureResult<Option<ClientRevisionWSData>, FlowyError> {
  112. let sink_provider = self.0.clone();
  113. FutureResult::new(async move { sink_provider.next().await })
  114. }
  115. }
  116. struct DocumentConflictResolver {
  117. edit_cmd_tx: EditorCommandSender,
  118. }
  119. impl ConflictResolver<DeltaDocumentResolveOperations> for DocumentConflictResolver {
  120. fn compose_operations(
  121. &self,
  122. operations: DeltaDocumentResolveOperations,
  123. ) -> BoxResultFuture<OperationsMD5, FlowyError> {
  124. let tx = self.edit_cmd_tx.clone();
  125. let operations = operations.into_inner();
  126. Box::pin(async move {
  127. let (ret, rx) = oneshot::channel();
  128. tx.send(EditorCommand::ComposeRemoteOperation {
  129. client_operations: operations,
  130. ret,
  131. })
  132. .await
  133. .map_err(internal_error)?;
  134. let md5 = rx
  135. .await
  136. .map_err(|e| FlowyError::internal().context(format!("Compose operations failed: {}", e)))??;
  137. Ok(md5)
  138. })
  139. }
  140. fn transform_operations(
  141. &self,
  142. operations: DeltaDocumentResolveOperations,
  143. ) -> BoxResultFuture<TransformOperations<DeltaDocumentResolveOperations>, FlowyError> {
  144. let tx = self.edit_cmd_tx.clone();
  145. let operations = operations.into_inner();
  146. Box::pin(async move {
  147. let (ret, rx) = oneshot::channel::<CollaborateResult<TextTransformOperations>>();
  148. tx.send(EditorCommand::TransformOperations { operations, ret })
  149. .await
  150. .map_err(internal_error)?;
  151. let transformed_operations = rx
  152. .await
  153. .map_err(|e| FlowyError::internal().context(format!("Transform operations failed: {}", e)))??;
  154. Ok(transformed_operations)
  155. })
  156. }
  157. fn reset_operations(
  158. &self,
  159. operations: DeltaDocumentResolveOperations,
  160. ) -> BoxResultFuture<OperationsMD5, FlowyError> {
  161. let tx = self.edit_cmd_tx.clone();
  162. let operations = operations.into_inner();
  163. Box::pin(async move {
  164. let (ret, rx) = oneshot::channel();
  165. let _ = tx
  166. .send(EditorCommand::ResetOperations { operations, ret })
  167. .await
  168. .map_err(internal_error)?;
  169. let md5 = rx
  170. .await
  171. .map_err(|e| FlowyError::internal().context(format!("Reset operations failed: {}", e)))??;
  172. Ok(md5)
  173. })
  174. }
  175. }