rev_manager.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 a list of revisions into one in `Bytes` format
  34. ///
  35. /// * `revisions`: a list of revisions will be serialized to `Bytes`
  36. ///
  37. fn combine_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.combine_revisions(revisions)?;
  59. Ok(Revision::new(object_id, base_rev_id, rev_id, bytes, user_id, md5))
  60. }
  61. fn combine_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_compress: 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_compress = Arc::new(rev_compress);
  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,
  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. pub async fn load_revisions(&self) -> FlowyResult<Vec<Revision>> {
  121. let revisions = RevisionLoader {
  122. object_id: self.object_id.clone(),
  123. user_id: self.user_id.clone(),
  124. cloud: None,
  125. rev_persistence: self.rev_persistence.clone(),
  126. }
  127. .load_revisions()
  128. .await?;
  129. Ok(revisions)
  130. }
  131. #[tracing::instrument(level = "debug", skip(self, revisions), err)]
  132. pub async fn reset_object(&self, revisions: RepeatedRevision) -> FlowyResult<()> {
  133. let rev_id = pair_rev_id_from_revisions(&revisions).1;
  134. let _ = self.rev_persistence.reset(revisions.into_inner()).await?;
  135. self.rev_id_counter.set(rev_id);
  136. Ok(())
  137. }
  138. #[tracing::instrument(level = "debug", skip(self, revision), err)]
  139. pub async fn add_remote_revision(&self, revision: &Revision) -> Result<(), FlowyError> {
  140. if revision.bytes.is_empty() {
  141. return Err(FlowyError::internal().context("Remote revisions is empty"));
  142. }
  143. let _ = self.rev_persistence.add_ack_revision(revision).await?;
  144. // self.rev_history.add_revision(revision).await;
  145. self.rev_id_counter.set(revision.rev_id);
  146. Ok(())
  147. }
  148. #[tracing::instrument(level = "debug", skip_all, err)]
  149. pub async fn add_local_revision(&self, revision: &Revision) -> Result<(), FlowyError> {
  150. if revision.bytes.is_empty() {
  151. return Err(FlowyError::internal().context("Local revisions is empty"));
  152. }
  153. let rev_id = self
  154. .rev_persistence
  155. .add_sync_revision(revision, &self.rev_compress)
  156. .await?;
  157. // self.rev_history.add_revision(revision).await;
  158. self.rev_id_counter.set(rev_id);
  159. Ok(())
  160. }
  161. #[tracing::instrument(level = "debug", skip(self), err)]
  162. pub async fn ack_revision(&self, rev_id: i64) -> Result<(), FlowyError> {
  163. if self.rev_persistence.ack_revision(rev_id).await.is_ok() {
  164. #[cfg(feature = "flowy_unit_test")]
  165. let _ = self.rev_ack_notifier.send(rev_id);
  166. }
  167. Ok(())
  168. }
  169. pub fn rev_id(&self) -> i64 {
  170. self.rev_id_counter.value()
  171. }
  172. pub fn next_rev_id_pair(&self) -> (i64, i64) {
  173. let cur = self.rev_id_counter.value();
  174. let next = self.rev_id_counter.next();
  175. (cur, next)
  176. }
  177. pub async fn get_revisions_in_range(&self, range: RevisionRange) -> Result<Vec<Revision>, FlowyError> {
  178. let revisions = self.rev_persistence.revisions_in_range(&range).await?;
  179. Ok(revisions)
  180. }
  181. pub async fn next_sync_revision(&self) -> FlowyResult<Option<Revision>> {
  182. self.rev_persistence.next_sync_revision().await
  183. }
  184. pub async fn get_revision(&self, rev_id: i64) -> Option<Revision> {
  185. self.rev_persistence.get(rev_id).await.map(|record| record.revision)
  186. }
  187. }
  188. impl WSDataProviderDataSource for Arc<RevisionManager> {
  189. fn next_revision(&self) -> FutureResult<Option<Revision>, FlowyError> {
  190. let rev_manager = self.clone();
  191. FutureResult::new(async move { rev_manager.next_sync_revision().await })
  192. }
  193. fn ack_revision(&self, rev_id: i64) -> FutureResult<(), FlowyError> {
  194. let rev_manager = self.clone();
  195. FutureResult::new(async move { (*rev_manager).ack_revision(rev_id).await })
  196. }
  197. fn current_rev_id(&self) -> i64 {
  198. self.rev_id()
  199. }
  200. }
  201. #[cfg(feature = "flowy_unit_test")]
  202. impl RevisionManager {
  203. pub async fn revision_cache(&self) -> Arc<RevisionPersistence> {
  204. self.rev_persistence.clone()
  205. }
  206. pub fn ack_notify(&self) -> tokio::sync::broadcast::Receiver<i64> {
  207. self.rev_ack_notifier.subscribe()
  208. }
  209. }
  210. pub struct RevisionLoader {
  211. pub object_id: String,
  212. pub user_id: String,
  213. pub cloud: Option<Arc<dyn RevisionCloudService>>,
  214. pub rev_persistence: Arc<RevisionPersistence>,
  215. }
  216. impl RevisionLoader {
  217. pub async fn load(&self) -> Result<(Vec<Revision>, i64), FlowyError> {
  218. let records = self.rev_persistence.batch_get(&self.object_id)?;
  219. let revisions: Vec<Revision>;
  220. let mut rev_id = 0;
  221. if records.is_empty() && self.cloud.is_some() {
  222. let remote_revisions = self
  223. .cloud
  224. .as_ref()
  225. .unwrap()
  226. .fetch_object(&self.user_id, &self.object_id)
  227. .await?;
  228. for revision in &remote_revisions {
  229. rev_id = revision.rev_id;
  230. let _ = self.rev_persistence.add_ack_revision(revision).await?;
  231. }
  232. revisions = remote_revisions;
  233. } else {
  234. for record in &records {
  235. rev_id = record.revision.rev_id;
  236. if record.state == RevisionState::Sync {
  237. // Sync the records if their state is RevisionState::Sync.
  238. let _ = self.rev_persistence.sync_revision(&record.revision).await?;
  239. }
  240. }
  241. revisions = records.into_iter().map(|record| record.revision).collect::<_>();
  242. }
  243. if let Some(revision) = revisions.last() {
  244. debug_assert_eq!(rev_id, revision.rev_id);
  245. }
  246. Ok((revisions, rev_id))
  247. }
  248. pub async fn load_revisions(&self) -> Result<Vec<Revision>, FlowyError> {
  249. let records = self.rev_persistence.batch_get(&self.object_id)?;
  250. let revisions = records.into_iter().map(|record| record.revision).collect::<_>();
  251. Ok(revisions)
  252. }
  253. }