rev_manager.rs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. use crate::disk::RevisionState;
  2. use crate::{RevisionPersistence, RevisionSnapshotDiskCache, RevisionSnapshotManager, WSDataProviderDataSource};
  3. use bytes::Bytes;
  4. use flowy_error::{FlowyError, FlowyResult};
  5. use flowy_sync::{
  6. entities::revision::{RepeatedRevision, Revision, RevisionRange},
  7. util::{pair_rev_id_from_revisions, RevIdCounter},
  8. };
  9. use lib_infra::future::FutureResult;
  10. use std::sync::Arc;
  11. pub trait RevisionCloudService: Send + Sync {
  12. /// Read the object's revision from remote
  13. /// Returns a list of revisions that used to build the object
  14. /// # Arguments
  15. ///
  16. /// * `user_id`: the id of the user
  17. /// * `object_id`: the id of the object
  18. ///
  19. fn fetch_object(&self, user_id: &str, object_id: &str) -> FutureResult<Vec<Revision>, FlowyError>;
  20. }
  21. pub trait RevisionObjectDeserializer: Send + Sync {
  22. type Output;
  23. /// Deserialize the list of revisions into an concrete object type.
  24. ///
  25. /// # Arguments
  26. ///
  27. /// * `object_id`: the id of the object
  28. /// * `revisions`: a list of revisions that represent the object
  29. ///
  30. fn deserialize_revisions(object_id: &str, revisions: Vec<Revision>) -> FlowyResult<Self::Output>;
  31. }
  32. pub trait RevisionObjectSerializer: Send + Sync {
  33. /// Serialize the list of revisions to `Bytes`
  34. ///
  35. /// * `revisions`: a list of revisions will be serialized to `Bytes`
  36. ///
  37. fn serialize_revisions(revisions: Vec<Revision>) -> FlowyResult<Bytes>;
  38. }
  39. /// `RevisionCompress` is used to compress multiple revisions into one revision
  40. ///
  41. pub trait RevisionCompress: Send + Sync {
  42. fn compress_revisions(
  43. &self,
  44. user_id: &str,
  45. object_id: &str,
  46. mut revisions: Vec<Revision>,
  47. ) -> FlowyResult<Revision> {
  48. if revisions.is_empty() {
  49. return Err(FlowyError::internal().context("Can't compact the empty revisions"));
  50. }
  51. if revisions.len() == 1 {
  52. return Ok(revisions.pop().unwrap());
  53. }
  54. let first_revision = revisions.first().unwrap();
  55. let last_revision = revisions.last().unwrap();
  56. let (base_rev_id, rev_id) = first_revision.pair_rev_id();
  57. let md5 = last_revision.md5.clone();
  58. let bytes = self.serialize_revisions(revisions)?;
  59. Ok(Revision::new(object_id, base_rev_id, rev_id, bytes, user_id, md5))
  60. }
  61. fn serialize_revisions(&self, revisions: Vec<Revision>) -> FlowyResult<Bytes>;
  62. }
  63. pub struct RevisionManager {
  64. pub object_id: String,
  65. user_id: String,
  66. rev_id_counter: RevIdCounter,
  67. rev_persistence: Arc<RevisionPersistence>,
  68. #[allow(dead_code)]
  69. rev_snapshot: Arc<RevisionSnapshotManager>,
  70. rev_compress: Arc<dyn RevisionCompress>,
  71. #[cfg(feature = "flowy_unit_test")]
  72. rev_ack_notifier: tokio::sync::broadcast::Sender<i64>,
  73. }
  74. impl RevisionManager {
  75. pub fn new<SP, C>(
  76. user_id: &str,
  77. object_id: &str,
  78. rev_persistence: RevisionPersistence,
  79. rev_compactor: C,
  80. snapshot_persistence: SP,
  81. ) -> Self
  82. where
  83. SP: 'static + RevisionSnapshotDiskCache,
  84. C: 'static + RevisionCompress,
  85. {
  86. let rev_id_counter = RevIdCounter::new(0);
  87. let rev_compactor = Arc::new(rev_compactor);
  88. let rev_persistence = Arc::new(rev_persistence);
  89. let rev_snapshot = Arc::new(RevisionSnapshotManager::new(user_id, object_id, snapshot_persistence));
  90. #[cfg(feature = "flowy_unit_test")]
  91. let (revision_ack_notifier, _) = tokio::sync::broadcast::channel(1);
  92. Self {
  93. object_id: object_id.to_string(),
  94. user_id: user_id.to_owned(),
  95. rev_id_counter,
  96. rev_persistence,
  97. rev_snapshot,
  98. rev_compress: rev_compactor,
  99. #[cfg(feature = "flowy_unit_test")]
  100. rev_ack_notifier: revision_ack_notifier,
  101. }
  102. }
  103. #[tracing::instrument(level = "debug", skip_all, fields(object_id) err)]
  104. pub async fn load<B>(&mut self, cloud: Option<Arc<dyn RevisionCloudService>>) -> FlowyResult<B::Output>
  105. where
  106. B: RevisionObjectDeserializer,
  107. {
  108. let (revisions, rev_id) = RevisionLoader {
  109. object_id: self.object_id.clone(),
  110. user_id: self.user_id.clone(),
  111. cloud,
  112. rev_persistence: self.rev_persistence.clone(),
  113. }
  114. .load()
  115. .await?;
  116. self.rev_id_counter.set(rev_id);
  117. tracing::Span::current().record("object_id", &self.object_id.as_str());
  118. B::deserialize_revisions(&self.object_id, revisions)
  119. }
  120. #[tracing::instrument(level = "debug", skip(self, revisions), err)]
  121. pub async fn reset_object(&self, revisions: RepeatedRevision) -> FlowyResult<()> {
  122. let rev_id = pair_rev_id_from_revisions(&revisions).1;
  123. let _ = self.rev_persistence.reset(revisions.into_inner()).await?;
  124. self.rev_id_counter.set(rev_id);
  125. Ok(())
  126. }
  127. #[tracing::instrument(level = "debug", skip(self, revision), err)]
  128. pub async fn add_remote_revision(&self, revision: &Revision) -> Result<(), FlowyError> {
  129. if revision.bytes.is_empty() {
  130. return Err(FlowyError::internal().context("Remote revisions is empty"));
  131. }
  132. let _ = self.rev_persistence.add_ack_revision(revision).await?;
  133. // self.rev_history.add_revision(revision).await;
  134. self.rev_id_counter.set(revision.rev_id);
  135. Ok(())
  136. }
  137. #[tracing::instrument(level = "debug", skip_all, err)]
  138. pub async fn add_local_revision(&self, revision: &Revision) -> Result<(), FlowyError> {
  139. if revision.bytes.is_empty() {
  140. return Err(FlowyError::internal().context("Local revisions is empty"));
  141. }
  142. let rev_id = self
  143. .rev_persistence
  144. .add_sync_revision(revision, &self.rev_compress)
  145. .await?;
  146. // self.rev_history.add_revision(revision).await;
  147. self.rev_id_counter.set(rev_id);
  148. Ok(())
  149. }
  150. #[tracing::instrument(level = "debug", skip(self), err)]
  151. pub async fn ack_revision(&self, rev_id: i64) -> Result<(), FlowyError> {
  152. if self.rev_persistence.ack_revision(rev_id).await.is_ok() {
  153. #[cfg(feature = "flowy_unit_test")]
  154. let _ = self.rev_ack_notifier.send(rev_id);
  155. }
  156. Ok(())
  157. }
  158. pub fn rev_id(&self) -> i64 {
  159. self.rev_id_counter.value()
  160. }
  161. pub fn next_rev_id_pair(&self) -> (i64, i64) {
  162. let cur = self.rev_id_counter.value();
  163. let next = self.rev_id_counter.next();
  164. (cur, next)
  165. }
  166. pub async fn get_revisions_in_range(&self, range: RevisionRange) -> Result<Vec<Revision>, FlowyError> {
  167. let revisions = self.rev_persistence.revisions_in_range(&range).await?;
  168. Ok(revisions)
  169. }
  170. pub async fn next_sync_revision(&self) -> FlowyResult<Option<Revision>> {
  171. self.rev_persistence.next_sync_revision().await
  172. }
  173. pub async fn get_revision(&self, rev_id: i64) -> Option<Revision> {
  174. self.rev_persistence.get(rev_id).await.map(|record| record.revision)
  175. }
  176. }
  177. impl WSDataProviderDataSource for Arc<RevisionManager> {
  178. fn next_revision(&self) -> FutureResult<Option<Revision>, FlowyError> {
  179. let rev_manager = self.clone();
  180. FutureResult::new(async move { rev_manager.next_sync_revision().await })
  181. }
  182. fn ack_revision(&self, rev_id: i64) -> FutureResult<(), FlowyError> {
  183. let rev_manager = self.clone();
  184. FutureResult::new(async move { (*rev_manager).ack_revision(rev_id).await })
  185. }
  186. fn current_rev_id(&self) -> i64 {
  187. self.rev_id()
  188. }
  189. }
  190. #[cfg(feature = "flowy_unit_test")]
  191. impl RevisionManager {
  192. pub async fn revision_cache(&self) -> Arc<RevisionPersistence> {
  193. self.rev_persistence.clone()
  194. }
  195. pub fn ack_notify(&self) -> tokio::sync::broadcast::Receiver<i64> {
  196. self.rev_ack_notifier.subscribe()
  197. }
  198. }
  199. pub struct RevisionLoader {
  200. pub object_id: String,
  201. pub user_id: String,
  202. pub cloud: Option<Arc<dyn RevisionCloudService>>,
  203. pub rev_persistence: Arc<RevisionPersistence>,
  204. }
  205. impl RevisionLoader {
  206. pub async fn load(&self) -> Result<(Vec<Revision>, i64), FlowyError> {
  207. let records = self.rev_persistence.batch_get(&self.object_id)?;
  208. let revisions: Vec<Revision>;
  209. let mut rev_id = 0;
  210. if records.is_empty() && self.cloud.is_some() {
  211. let remote_revisions = self
  212. .cloud
  213. .as_ref()
  214. .unwrap()
  215. .fetch_object(&self.user_id, &self.object_id)
  216. .await?;
  217. for revision in &remote_revisions {
  218. rev_id = revision.rev_id;
  219. let _ = self.rev_persistence.add_ack_revision(revision).await?;
  220. }
  221. revisions = remote_revisions;
  222. } else {
  223. for record in &records {
  224. rev_id = record.revision.rev_id;
  225. if record.state == RevisionState::Sync {
  226. // Sync the records if their state is RevisionState::Sync.
  227. let _ = self.rev_persistence.sync_revision(&record.revision).await?;
  228. }
  229. }
  230. revisions = records.into_iter().map(|record| record.revision).collect::<_>();
  231. }
  232. if let Some(revision) = revisions.last() {
  233. debug_assert_eq!(rev_id, revision.rev_id);
  234. }
  235. Ok((revisions, rev_id))
  236. }
  237. }