manager.rs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. use std::collections::HashMap;
  2. use std::ops::Deref;
  3. use std::sync::Arc;
  4. use appflowy_integrate::collab_builder::AppFlowyCollabBuilder;
  5. use appflowy_integrate::{RocksCollabDB, RocksDBConfig};
  6. use collab::core::collab::MutexCollab;
  7. use collab_database::database::DatabaseData;
  8. use collab_database::user::{UserDatabase as InnerUserDatabase, UserDatabaseCollabBuilder};
  9. use collab_database::views::{CreateDatabaseParams, CreateViewParams};
  10. use parking_lot::Mutex;
  11. use tokio::sync::RwLock;
  12. use flowy_error::{FlowyError, FlowyResult};
  13. use flowy_task::TaskDispatcher;
  14. use crate::entities::{DatabaseDescriptionPB, DatabaseLayoutPB, RepeatedDatabaseDescriptionPB};
  15. use crate::services::database::{DatabaseEditor, MutexDatabase};
  16. pub trait DatabaseUser2: Send + Sync {
  17. fn user_id(&self) -> Result<i64, FlowyError>;
  18. fn token(&self) -> Result<String, FlowyError>;
  19. fn collab_db(&self) -> Result<Arc<RocksCollabDB>, FlowyError>;
  20. }
  21. pub struct DatabaseManager2 {
  22. user: Arc<dyn DatabaseUser2>,
  23. user_database: UserDatabase,
  24. task_scheduler: Arc<RwLock<TaskDispatcher>>,
  25. editors: RwLock<HashMap<String, Arc<DatabaseEditor>>>,
  26. collab_builder: Arc<AppFlowyCollabBuilder>,
  27. }
  28. impl DatabaseManager2 {
  29. pub fn new(
  30. database_user: Arc<dyn DatabaseUser2>,
  31. task_scheduler: Arc<RwLock<TaskDispatcher>>,
  32. collab_builder: Arc<AppFlowyCollabBuilder>,
  33. ) -> Self {
  34. Self {
  35. user: database_user,
  36. user_database: UserDatabase::default(),
  37. task_scheduler,
  38. editors: Default::default(),
  39. collab_builder,
  40. }
  41. }
  42. pub async fn initialize(&self, user_id: i64, _token: &str) -> FlowyResult<()> {
  43. let db = self.user.collab_db()?;
  44. *self.user_database.lock() = Some(InnerUserDatabase::new(
  45. user_id,
  46. db,
  47. RocksDBConfig::default(),
  48. UserDatabaseCollabBuilderImpl(self.collab_builder.clone()),
  49. ));
  50. // do nothing
  51. Ok(())
  52. }
  53. pub async fn initialize_with_new_user(&self, user_id: i64, token: &str) -> FlowyResult<()> {
  54. self.initialize(user_id, token).await?;
  55. Ok(())
  56. }
  57. pub async fn get_all_databases_description(&self) -> RepeatedDatabaseDescriptionPB {
  58. let databases_description = self.with_user_database(vec![], |database| {
  59. database
  60. .get_all_databases()
  61. .into_iter()
  62. .map(DatabaseDescriptionPB::from)
  63. .collect()
  64. });
  65. RepeatedDatabaseDescriptionPB {
  66. items: databases_description,
  67. }
  68. }
  69. pub async fn get_database(&self, view_id: &str) -> FlowyResult<Arc<DatabaseEditor>> {
  70. let database_id = self.with_user_database(Err(FlowyError::internal()), |database| {
  71. database
  72. .get_database_id_with_view_id(view_id)
  73. .ok_or_else(FlowyError::record_not_found)
  74. })?;
  75. if let Some(editor) = self.editors.read().await.get(&database_id) {
  76. return Ok(editor.clone());
  77. }
  78. let mut editors = self.editors.write().await;
  79. let database = MutexDatabase::new(self.with_user_database(
  80. Err(FlowyError::record_not_found()),
  81. |database| {
  82. database
  83. .get_database(&database_id)
  84. .ok_or_else(FlowyError::record_not_found)
  85. },
  86. )?);
  87. let editor = Arc::new(DatabaseEditor::new(database, self.task_scheduler.clone()).await?);
  88. editors.insert(database_id.to_string(), editor.clone());
  89. Ok(editor)
  90. }
  91. #[tracing::instrument(level = "debug", skip_all)]
  92. pub async fn close_database_view<T: AsRef<str>>(&self, view_id: T) -> FlowyResult<()> {
  93. let view_id = view_id.as_ref();
  94. let database_id = self.with_user_database(None, |database| {
  95. database.get_database_id_with_view_id(view_id)
  96. });
  97. if let Some(database_id) = database_id {
  98. let mut editors = self.editors.write().await;
  99. if let Some(editor) = editors.get(&database_id) {
  100. if editor.close_view_editor(view_id).await {
  101. editor.close().await;
  102. editors.remove(&database_id);
  103. }
  104. }
  105. }
  106. Ok(())
  107. }
  108. pub async fn duplicate_database(&self, view_id: &str) -> FlowyResult<Vec<u8>> {
  109. let database_data = self.with_user_database(Err(FlowyError::internal()), |database| {
  110. let data = database.get_database_duplicated_data(view_id)?;
  111. let json_bytes = data.to_json_bytes()?;
  112. Ok(json_bytes)
  113. })?;
  114. Ok(database_data)
  115. }
  116. #[tracing::instrument(level = "trace", skip_all, err)]
  117. pub async fn create_database_with_database_data(
  118. &self,
  119. view_id: &str,
  120. data: Vec<u8>,
  121. ) -> FlowyResult<()> {
  122. let mut database_data = DatabaseData::from_json_bytes(data)?;
  123. database_data.view.id = view_id.to_string();
  124. self.with_user_database(
  125. Err(FlowyError::internal().context("Create database with data failed")),
  126. |database| {
  127. let database = database.create_database_with_data(database_data)?;
  128. Ok(database)
  129. },
  130. )?;
  131. Ok(())
  132. }
  133. pub async fn create_database_with_params(&self, params: CreateDatabaseParams) -> FlowyResult<()> {
  134. let _ = self.with_user_database(
  135. Err(FlowyError::internal().context("Create database with params failed")),
  136. |user_database| {
  137. let database = user_database.create_database(params)?;
  138. Ok(database)
  139. },
  140. )?;
  141. Ok(())
  142. }
  143. pub async fn create_linked_view(
  144. &self,
  145. name: String,
  146. layout: DatabaseLayoutPB,
  147. database_id: String,
  148. target_view_id: String,
  149. duplicated_view_id: Option<String>,
  150. ) -> FlowyResult<()> {
  151. self.with_user_database(
  152. Err(FlowyError::internal().context("Create database view failed")),
  153. |user_database| {
  154. let database = user_database
  155. .get_database(&database_id)
  156. .ok_or_else(FlowyError::record_not_found)?;
  157. match duplicated_view_id {
  158. None => {
  159. let params = CreateViewParams::new(database_id, target_view_id, name, layout.into());
  160. database.create_linked_view(params);
  161. },
  162. Some(duplicated_view_id) => {
  163. database.duplicate_linked_view(&duplicated_view_id);
  164. },
  165. }
  166. Ok(())
  167. },
  168. )?;
  169. Ok(())
  170. }
  171. fn with_user_database<F, Output>(&self, default_value: Output, f: F) -> Output
  172. where
  173. F: FnOnce(&InnerUserDatabase) -> Output,
  174. {
  175. let database = self.user_database.lock();
  176. match &*database {
  177. None => default_value,
  178. Some(folder) => f(folder),
  179. }
  180. }
  181. }
  182. #[derive(Clone, Default)]
  183. pub struct UserDatabase(Arc<Mutex<Option<InnerUserDatabase>>>);
  184. impl Deref for UserDatabase {
  185. type Target = Arc<Mutex<Option<InnerUserDatabase>>>;
  186. fn deref(&self) -> &Self::Target {
  187. &self.0
  188. }
  189. }
  190. unsafe impl Sync for UserDatabase {}
  191. unsafe impl Send for UserDatabase {}
  192. struct UserDatabaseCollabBuilderImpl(Arc<AppFlowyCollabBuilder>);
  193. impl UserDatabaseCollabBuilder for UserDatabaseCollabBuilderImpl {
  194. fn build(&self, uid: i64, object_id: &str, db: Arc<RocksCollabDB>) -> Arc<MutexCollab> {
  195. self.0.build(uid, object_id, db)
  196. }
  197. fn build_with_config(
  198. &self,
  199. uid: i64,
  200. object_id: &str,
  201. db: Arc<RocksCollabDB>,
  202. config: &RocksDBConfig,
  203. ) -> Arc<MutexCollab> {
  204. self.0.build_with_config(uid, object_id, db, config)
  205. }
  206. }