conflict_resolve.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. use crate::{RevisionMD5, RevisionManager};
  2. use bytes::Bytes;
  3. use flowy_error::{FlowyError, FlowyResult};
  4. use lib_infra::future::BoxResultFuture;
  5. use revision_model::{Revision, RevisionRange};
  6. use std::sync::Arc;
  7. pub struct TransformOperations<Operations> {
  8. pub client_operations: Operations,
  9. pub server_operations: Option<Operations>,
  10. }
  11. pub trait OperationsDeserializer<T>: Send + Sync {
  12. fn deserialize_revisions(revisions: Vec<Revision>) -> FlowyResult<T>;
  13. }
  14. pub trait OperationsSerializer: Send + Sync {
  15. fn serialize_operations(&self) -> Bytes;
  16. }
  17. pub struct ConflictOperations<T>(T);
  18. pub trait ConflictResolver<Operations>
  19. where
  20. Operations: Send + Sync,
  21. {
  22. fn compose_operations(&self, operations: Operations) -> BoxResultFuture<RevisionMD5, FlowyError>;
  23. fn transform_operations(
  24. &self,
  25. operations: Operations,
  26. ) -> BoxResultFuture<TransformOperations<Operations>, FlowyError>;
  27. fn reset_operations(&self, operations: Operations) -> BoxResultFuture<RevisionMD5, FlowyError>;
  28. }
  29. pub trait ConflictRevisionSink: Send + Sync + 'static {
  30. fn send(&self, revisions: Vec<Revision>) -> BoxResultFuture<(), FlowyError>;
  31. fn ack(&self, rev_id: i64) -> BoxResultFuture<(), FlowyError>;
  32. }
  33. pub struct ConflictController<Operations, Connection>
  34. where
  35. Operations: Send + Sync,
  36. {
  37. user_id: String,
  38. resolver: Arc<dyn ConflictResolver<Operations> + Send + Sync>,
  39. rev_sink: Arc<dyn ConflictRevisionSink>,
  40. rev_manager: Arc<RevisionManager<Connection>>,
  41. }
  42. impl<Operations, Connection> ConflictController<Operations, Connection>
  43. where
  44. Operations: Clone + Send + Sync,
  45. Connection: 'static,
  46. {
  47. pub fn new(
  48. user_id: &str,
  49. resolver: Arc<dyn ConflictResolver<Operations> + Send + Sync>,
  50. rev_sink: Arc<dyn ConflictRevisionSink>,
  51. rev_manager: Arc<RevisionManager<Connection>>,
  52. ) -> Self {
  53. let user_id = user_id.to_owned();
  54. Self {
  55. user_id,
  56. resolver,
  57. rev_sink,
  58. rev_manager,
  59. }
  60. }
  61. }
  62. impl<Operations, Connection> ConflictController<Operations, Connection>
  63. where
  64. Operations: OperationsSerializer + OperationsDeserializer<Operations> + Clone + Send + Sync,
  65. Connection: Send + Sync + 'static,
  66. {
  67. pub async fn receive_revisions(&self, revisions: Vec<Revision>) -> FlowyResult<()> {
  68. if revisions.is_empty() {
  69. return Ok(());
  70. }
  71. match self.handle_revision(revisions).await? {
  72. None => {},
  73. Some(server_revision) => {
  74. self.rev_sink.send(vec![server_revision]).await?;
  75. },
  76. }
  77. Ok(())
  78. }
  79. pub async fn ack_revision(&self, rev_id: i64) -> FlowyResult<()> {
  80. self.rev_sink.ack(rev_id).await?;
  81. Ok(())
  82. }
  83. pub async fn send_revisions(&self, range: RevisionRange) -> FlowyResult<()> {
  84. let revisions = self.rev_manager.get_revisions_in_range(range).await?;
  85. self.rev_sink.send(revisions).await?;
  86. Ok(())
  87. }
  88. async fn handle_revision(&self, mut revisions: Vec<Revision>) -> FlowyResult<Option<Revision>> {
  89. let first_revision = revisions.first().unwrap();
  90. if let Some(local_revision) = self.rev_manager.get_revision(first_revision.rev_id).await {
  91. if local_revision.md5 == first_revision.md5 {
  92. // The local revision is equal to the pushed revision. Just ignore it.
  93. revisions = revisions.split_off(1);
  94. if revisions.is_empty() {
  95. return Ok(None);
  96. }
  97. } else {
  98. return Ok(None);
  99. }
  100. }
  101. let new_operations = Operations::deserialize_revisions(revisions.clone())?;
  102. let TransformOperations {
  103. client_operations,
  104. server_operations,
  105. } = self.resolver.transform_operations(new_operations).await?;
  106. match server_operations {
  107. None => {
  108. // The server_prime is None means the client local revisions conflict with the
  109. // // server, and it needs to override the client delta.
  110. let md5 = self.resolver.reset_operations(client_operations).await?;
  111. debug_assert!(md5.is_equal(&revisions.last().unwrap().md5));
  112. self.rev_manager.reset_object(revisions).await?;
  113. Ok(None)
  114. },
  115. Some(server_operations) => {
  116. let md5 = self
  117. .resolver
  118. .compose_operations(client_operations.clone())
  119. .await?;
  120. for revision in &revisions {
  121. self.rev_manager.add_remote_revision(revision).await?;
  122. }
  123. let (client_revision, server_revision) = make_client_and_server_revision(
  124. &self.user_id,
  125. &self.rev_manager,
  126. client_operations,
  127. Some(server_operations),
  128. md5,
  129. );
  130. self
  131. .rev_manager
  132. .add_remote_revision(&client_revision)
  133. .await?;
  134. Ok(server_revision)
  135. },
  136. }
  137. }
  138. }
  139. fn make_client_and_server_revision<Operations, Connection>(
  140. _user_id: &str,
  141. rev_manager: &Arc<RevisionManager<Connection>>,
  142. client_operations: Operations,
  143. server_operations: Option<Operations>,
  144. md5: RevisionMD5,
  145. ) -> (Revision, Option<Revision>)
  146. where
  147. Operations: OperationsSerializer,
  148. Connection: 'static,
  149. {
  150. let (base_rev_id, rev_id) = rev_manager.next_rev_id_pair();
  151. let bytes = client_operations.serialize_operations();
  152. let client_revision = Revision::new(
  153. &rev_manager.object_id,
  154. base_rev_id,
  155. rev_id,
  156. bytes,
  157. md5.clone(),
  158. );
  159. match server_operations {
  160. None => (client_revision, None),
  161. Some(operations) => {
  162. let bytes = operations.serialize_operations();
  163. let server_revision = Revision::new(&rev_manager.object_id, base_rev_id, rev_id, bytes, md5);
  164. (client_revision, Some(server_revision))
  165. },
  166. }
  167. }