block_editor.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. use crate::entities::RowPB;
  2. use bytes::Bytes;
  3. use flowy_error::{FlowyError, FlowyResult};
  4. use flowy_http_model::revision::Revision;
  5. use flowy_revision::{
  6. RevisionCloudService, RevisionManager, RevisionMergeable, RevisionObjectDeserializer, RevisionObjectSerializer,
  7. };
  8. use flowy_sync::client_grid::{GridBlockRevisionChangeset, GridBlockRevisionPad};
  9. use flowy_sync::util::make_operations_from_revisions;
  10. use grid_rev_model::{CellRevision, GridBlockRevision, RowChangeset, RowRevision};
  11. use lib_infra::future::FutureResult;
  12. use flowy_database::ConnectionPool;
  13. use lib_ot::core::EmptyAttributes;
  14. use std::borrow::Cow;
  15. use std::sync::Arc;
  16. use tokio::sync::RwLock;
  17. pub struct GridBlockRevisionEditor {
  18. #[allow(dead_code)]
  19. user_id: String,
  20. pub block_id: String,
  21. pad: Arc<RwLock<GridBlockRevisionPad>>,
  22. rev_manager: Arc<RevisionManager<Arc<ConnectionPool>>>,
  23. }
  24. impl GridBlockRevisionEditor {
  25. pub async fn new(
  26. user_id: &str,
  27. token: &str,
  28. block_id: &str,
  29. mut rev_manager: RevisionManager<Arc<ConnectionPool>>,
  30. ) -> FlowyResult<Self> {
  31. let cloud = Arc::new(GridBlockRevisionCloudService {
  32. token: token.to_owned(),
  33. });
  34. let block_revision_pad = rev_manager.initialize::<GridBlockRevisionSerde>(Some(cloud)).await?;
  35. let pad = Arc::new(RwLock::new(block_revision_pad));
  36. let rev_manager = Arc::new(rev_manager);
  37. let user_id = user_id.to_owned();
  38. let block_id = block_id.to_owned();
  39. Ok(Self {
  40. user_id,
  41. block_id,
  42. pad,
  43. rev_manager,
  44. })
  45. }
  46. pub async fn duplicate_block(&self, duplicated_block_id: &str) -> GridBlockRevision {
  47. self.pad.read().await.duplicate_data(duplicated_block_id).await
  48. }
  49. /// Create a row after the the with prev_row_id. If prev_row_id is None, the row will be appended to the list
  50. pub(crate) async fn create_row(
  51. &self,
  52. row: RowRevision,
  53. prev_row_id: Option<String>,
  54. ) -> FlowyResult<(i32, Option<i32>)> {
  55. let mut row_count = 0;
  56. let mut row_index = None;
  57. let _ = self
  58. .modify(|block_pad| {
  59. if let Some(start_row_id) = prev_row_id.as_ref() {
  60. match block_pad.index_of_row(start_row_id) {
  61. None => {}
  62. Some(index) => row_index = Some(index as i32 + 1),
  63. }
  64. }
  65. let change = block_pad.add_row_rev(row, prev_row_id)?;
  66. row_count = block_pad.number_of_rows();
  67. if row_index.is_none() {
  68. row_index = Some(row_count - 1);
  69. }
  70. Ok(change)
  71. })
  72. .await?;
  73. Ok((row_count, row_index))
  74. }
  75. pub async fn delete_rows(&self, ids: Vec<Cow<'_, String>>) -> FlowyResult<i32> {
  76. let mut row_count = 0;
  77. let _ = self
  78. .modify(|block_pad| {
  79. let changeset = block_pad.delete_rows(ids)?;
  80. row_count = block_pad.number_of_rows();
  81. Ok(changeset)
  82. })
  83. .await?;
  84. Ok(row_count)
  85. }
  86. pub async fn update_row(&self, changeset: RowChangeset) -> FlowyResult<()> {
  87. let _ = self.modify(|block_pad| Ok(block_pad.update_row(changeset)?)).await?;
  88. Ok(())
  89. }
  90. pub async fn move_row(&self, row_id: &str, from: usize, to: usize) -> FlowyResult<()> {
  91. let _ = self
  92. .modify(|block_pad| Ok(block_pad.move_row(row_id, from, to)?))
  93. .await?;
  94. Ok(())
  95. }
  96. pub async fn index_of_row(&self, row_id: &str) -> Option<usize> {
  97. self.pad.read().await.index_of_row(row_id)
  98. }
  99. pub async fn get_row_rev(&self, row_id: &str) -> FlowyResult<Option<(usize, Arc<RowRevision>)>> {
  100. let row_rev = self.pad.read().await.get_row_rev(row_id);
  101. Ok(row_rev)
  102. }
  103. pub async fn get_row_revs<T>(&self, row_ids: Option<Vec<Cow<'_, T>>>) -> FlowyResult<Vec<Arc<RowRevision>>>
  104. where
  105. T: AsRef<str> + ToOwned + ?Sized,
  106. {
  107. let row_revs = self.pad.read().await.get_row_revs(row_ids)?;
  108. Ok(row_revs)
  109. }
  110. pub async fn get_cell_revs(
  111. &self,
  112. field_id: &str,
  113. row_ids: Option<Vec<Cow<'_, String>>>,
  114. ) -> FlowyResult<Vec<CellRevision>> {
  115. let cell_revs = self.pad.read().await.get_cell_revs(field_id, row_ids)?;
  116. Ok(cell_revs)
  117. }
  118. pub async fn get_row_pb(&self, row_id: &str) -> FlowyResult<Option<RowPB>> {
  119. let row_ids = Some(vec![Cow::Borrowed(row_id)]);
  120. Ok(self.get_row_pbs(row_ids).await?.pop())
  121. }
  122. pub async fn get_row_pbs<T>(&self, row_ids: Option<Vec<Cow<'_, T>>>) -> FlowyResult<Vec<RowPB>>
  123. where
  124. T: AsRef<str> + ToOwned + ?Sized,
  125. {
  126. let row_infos = self
  127. .pad
  128. .read()
  129. .await
  130. .get_row_revs(row_ids)?
  131. .iter()
  132. .map(RowPB::from)
  133. .collect::<Vec<RowPB>>();
  134. Ok(row_infos)
  135. }
  136. async fn modify<F>(&self, f: F) -> FlowyResult<()>
  137. where
  138. F: for<'a> FnOnce(&'a mut GridBlockRevisionPad) -> FlowyResult<Option<GridBlockRevisionChangeset>>,
  139. {
  140. let mut write_guard = self.pad.write().await;
  141. match f(&mut *write_guard)? {
  142. None => {}
  143. Some(change) => {
  144. let _ = self.apply_change(change).await?;
  145. }
  146. }
  147. Ok(())
  148. }
  149. async fn apply_change(&self, change: GridBlockRevisionChangeset) -> FlowyResult<()> {
  150. let GridBlockRevisionChangeset { operations: delta, md5 } = change;
  151. let (base_rev_id, rev_id) = self.rev_manager.next_rev_id_pair();
  152. let delta_data = delta.json_bytes();
  153. let revision = Revision::new(&self.rev_manager.object_id, base_rev_id, rev_id, delta_data, md5);
  154. let _ = self.rev_manager.add_local_revision(&revision).await?;
  155. Ok(())
  156. }
  157. }
  158. struct GridBlockRevisionCloudService {
  159. #[allow(dead_code)]
  160. token: String,
  161. }
  162. impl RevisionCloudService for GridBlockRevisionCloudService {
  163. #[tracing::instrument(level = "trace", skip(self))]
  164. fn fetch_object(&self, _user_id: &str, _object_id: &str) -> FutureResult<Vec<Revision>, FlowyError> {
  165. FutureResult::new(async move { Ok(vec![]) })
  166. }
  167. }
  168. struct GridBlockRevisionSerde();
  169. impl RevisionObjectDeserializer for GridBlockRevisionSerde {
  170. type Output = GridBlockRevisionPad;
  171. fn deserialize_revisions(object_id: &str, revisions: Vec<Revision>) -> FlowyResult<Self::Output> {
  172. let pad = GridBlockRevisionPad::from_revisions(object_id, revisions)?;
  173. Ok(pad)
  174. }
  175. }
  176. impl RevisionObjectSerializer for GridBlockRevisionSerde {
  177. fn combine_revisions(revisions: Vec<Revision>) -> FlowyResult<Bytes> {
  178. let operations = make_operations_from_revisions::<EmptyAttributes>(revisions)?;
  179. Ok(operations.json_bytes())
  180. }
  181. }
  182. pub struct GridBlockRevisionCompress();
  183. impl RevisionMergeable for GridBlockRevisionCompress {
  184. fn combine_revisions(&self, revisions: Vec<Revision>) -> FlowyResult<Bytes> {
  185. GridBlockRevisionSerde::combine_revisions(revisions)
  186. }
  187. }