manager.rs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. use std::sync::Weak;
  2. use std::{collections::HashMap, sync::Arc};
  3. use collab::core::collab::MutexCollab;
  4. use collab_document::blocks::DocumentData;
  5. use collab_document::document::Document;
  6. use collab_document::document_data::default_document_data;
  7. use collab_document::YrsDocAction;
  8. use collab_entity::CollabType;
  9. use parking_lot::RwLock;
  10. use tracing::instrument;
  11. use collab_integrate::collab_builder::AppFlowyCollabBuilder;
  12. use collab_integrate::RocksCollabDB;
  13. use flowy_document_deps::cloud::DocumentCloudService;
  14. use flowy_error::{internal_error, FlowyError, FlowyResult};
  15. use flowy_storage::FileStorageService;
  16. use crate::document::MutexDocument;
  17. use crate::entities::DocumentSnapshotPB;
  18. use crate::reminder::DocumentReminderAction;
  19. pub trait DocumentUser: Send + Sync {
  20. fn user_id(&self) -> Result<i64, FlowyError>;
  21. fn token(&self) -> Result<Option<String>, FlowyError>; // unused now.
  22. fn collab_db(&self, uid: i64) -> Result<Weak<RocksCollabDB>, FlowyError>;
  23. }
  24. pub struct DocumentManager {
  25. pub user: Arc<dyn DocumentUser>,
  26. collab_builder: Arc<AppFlowyCollabBuilder>,
  27. documents: Arc<RwLock<HashMap<String, Arc<MutexDocument>>>>,
  28. #[allow(dead_code)]
  29. cloud_service: Arc<dyn DocumentCloudService>,
  30. storage_service: Weak<dyn FileStorageService>,
  31. }
  32. impl DocumentManager {
  33. pub fn new(
  34. user: Arc<dyn DocumentUser>,
  35. collab_builder: Arc<AppFlowyCollabBuilder>,
  36. cloud_service: Arc<dyn DocumentCloudService>,
  37. storage_service: Weak<dyn FileStorageService>,
  38. ) -> Self {
  39. Self {
  40. user,
  41. collab_builder,
  42. documents: Default::default(),
  43. cloud_service,
  44. storage_service,
  45. }
  46. }
  47. pub async fn initialize(&self, _uid: i64, _workspace_id: String) -> FlowyResult<()> {
  48. self.documents.write().clear();
  49. Ok(())
  50. }
  51. #[instrument(level = "debug", skip_all, err)]
  52. pub async fn initialize_with_new_user(&self, uid: i64, workspace_id: String) -> FlowyResult<()> {
  53. self.initialize(uid, workspace_id).await?;
  54. Ok(())
  55. }
  56. pub async fn handle_reminder_action(&self, action: DocumentReminderAction) {
  57. match action {
  58. DocumentReminderAction::Add { reminder: _ } => {},
  59. DocumentReminderAction::Remove { reminder_id: _ } => {},
  60. DocumentReminderAction::Update { reminder: _ } => {},
  61. }
  62. }
  63. /// Create a new document.
  64. ///
  65. /// if the document already exists, return the existing document.
  66. /// if the data is None, will create a document with default data.
  67. pub async fn create_document(
  68. &self,
  69. uid: i64,
  70. doc_id: &str,
  71. data: Option<DocumentData>,
  72. ) -> FlowyResult<Arc<MutexDocument>> {
  73. tracing::trace!("create a document: {:?}", doc_id);
  74. if self.is_doc_exist(doc_id).unwrap_or(false) {
  75. self.get_document(doc_id).await
  76. } else {
  77. let collab = self.collab_for_document(uid, doc_id, vec![]).await?;
  78. let data = data.unwrap_or_else(default_document_data);
  79. let document = Arc::new(MutexDocument::create_with_data(collab, data)?);
  80. Ok(document)
  81. }
  82. }
  83. /// Return the document
  84. #[tracing::instrument(level = "debug", skip(self), err)]
  85. pub async fn get_document(&self, doc_id: &str) -> FlowyResult<Arc<MutexDocument>> {
  86. if let Some(doc) = self.documents.read().get(doc_id) {
  87. return Ok(doc.clone());
  88. }
  89. let mut updates = vec![];
  90. if !self.is_doc_exist(doc_id)? {
  91. // Try to get the document from the cloud service
  92. updates = self.cloud_service.get_document_updates(doc_id).await?;
  93. }
  94. let uid = self.user.user_id()?;
  95. let collab = self.collab_for_document(uid, doc_id, updates).await?;
  96. let document = Arc::new(MutexDocument::open(doc_id, collab)?);
  97. // save the document to the memory and read it from the memory if we open the same document again.
  98. // and we don't want to subscribe to the document changes if we open the same document again.
  99. self
  100. .documents
  101. .write()
  102. .insert(doc_id.to_string(), document.clone());
  103. Ok(document)
  104. }
  105. pub async fn get_document_data(&self, doc_id: &str) -> FlowyResult<DocumentData> {
  106. let mut updates = vec![];
  107. if !self.is_doc_exist(doc_id)? {
  108. updates = self.cloud_service.get_document_updates(doc_id).await?;
  109. }
  110. let uid = self.user.user_id()?;
  111. let collab = self.collab_for_document(uid, doc_id, updates).await?;
  112. Document::open(collab)?
  113. .get_document_data()
  114. .map_err(internal_error)
  115. }
  116. pub fn close_document(&self, doc_id: &str) -> FlowyResult<()> {
  117. self.documents.write().remove(doc_id);
  118. Ok(())
  119. }
  120. pub fn delete_document(&self, doc_id: &str) -> FlowyResult<()> {
  121. let uid = self.user.user_id()?;
  122. if let Some(db) = self.user.collab_db(uid)?.upgrade() {
  123. let _ = db.with_write_txn(|txn| {
  124. txn.delete_doc(uid, &doc_id)?;
  125. Ok(())
  126. });
  127. self.documents.write().remove(doc_id);
  128. }
  129. Ok(())
  130. }
  131. /// Return the list of snapshots of the document.
  132. pub async fn get_document_snapshots(
  133. &self,
  134. document_id: &str,
  135. limit: usize,
  136. ) -> FlowyResult<Vec<DocumentSnapshotPB>> {
  137. let snapshots = self
  138. .cloud_service
  139. .get_document_snapshots(document_id, limit)
  140. .await?
  141. .into_iter()
  142. .map(|snapshot| DocumentSnapshotPB {
  143. snapshot_id: snapshot.snapshot_id,
  144. snapshot_desc: "".to_string(),
  145. created_at: snapshot.created_at,
  146. data: snapshot.data,
  147. })
  148. .collect::<Vec<_>>();
  149. Ok(snapshots)
  150. }
  151. async fn collab_for_document(
  152. &self,
  153. uid: i64,
  154. doc_id: &str,
  155. updates: Vec<Vec<u8>>,
  156. ) -> FlowyResult<Arc<MutexCollab>> {
  157. let db = self.user.collab_db(uid)?;
  158. let collab = self
  159. .collab_builder
  160. .build(uid, doc_id, CollabType::Document, updates, db)
  161. .await?;
  162. Ok(collab)
  163. // let doc_id = doc_id.to_string();
  164. // let (tx, rx) = oneshot::channel();
  165. // let collab_builder = self.collab_builder.clone();
  166. // tokio::spawn(async move {
  167. // let collab = collab_builder
  168. // .build(uid, &doc_id, CollabType::Document, updates, db)
  169. // .await
  170. // .unwrap();
  171. // let _ = tx.send(collab);
  172. // });
  173. //
  174. // Ok(rx.await.unwrap())
  175. }
  176. fn is_doc_exist(&self, doc_id: &str) -> FlowyResult<bool> {
  177. let uid = self.user.user_id()?;
  178. if let Some(collab_db) = self.user.collab_db(uid)?.upgrade() {
  179. let read_txn = collab_db.read_txn();
  180. Ok(read_txn.is_exist(uid, doc_id))
  181. } else {
  182. Ok(false)
  183. }
  184. }
  185. /// Only expose this method for testing
  186. #[cfg(debug_assertions)]
  187. pub fn get_cloud_service(&self) -> &Arc<dyn DocumentCloudService> {
  188. &self.cloud_service
  189. }
  190. /// Only expose this method for testing
  191. #[cfg(debug_assertions)]
  192. pub fn get_file_storage_service(&self) -> &Weak<dyn FileStorageService> {
  193. &self.storage_service
  194. }
  195. }