manager.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. use crate::editor::{initial_document_content, AppFlowyDocumentEditor, DocumentRevisionMergeable};
  2. use crate::entities::{DocumentVersionPB, EditParams};
  3. use crate::old_editor::editor::{DeltaDocumentEditor, DeltaDocumentRevisionMergeable};
  4. use crate::old_editor::snapshot::DeltaDocumentSnapshotPersistence;
  5. use crate::services::rev_sqlite::{
  6. SQLiteDeltaDocumentRevisionPersistence, SQLiteDocumentRevisionPersistence,
  7. SQLiteDocumentRevisionSnapshotPersistence,
  8. };
  9. use crate::services::DocumentPersistence;
  10. use crate::{errors::FlowyError, DocumentCloudService};
  11. use bytes::Bytes;
  12. use document_model::document::DocumentId;
  13. use flowy_client_sync::client_document::initial_delta_document_content;
  14. use flowy_error::FlowyResult;
  15. use flowy_revision::{
  16. RevisionCloudService, RevisionManager, RevisionPersistence, RevisionPersistenceConfiguration, RevisionWebSocket,
  17. };
  18. use flowy_sqlite::ConnectionPool;
  19. use lib_infra::async_trait::async_trait;
  20. use lib_infra::future::FutureResult;
  21. use lib_infra::ref_map::{RefCountHashMap, RefCountValue};
  22. use lib_infra::util::md5;
  23. use lib_ws::WSConnectState;
  24. use revision_model::Revision;
  25. use std::any::Any;
  26. use std::convert::TryFrom;
  27. use std::sync::Arc;
  28. use tokio::sync::RwLock;
  29. use ws_model::ws_revision::ServerRevisionWSData;
  30. pub trait DocumentUser: Send + Sync {
  31. fn user_dir(&self) -> Result<String, FlowyError>;
  32. fn user_id(&self) -> Result<String, FlowyError>;
  33. fn token(&self) -> Result<String, FlowyError>;
  34. }
  35. pub trait DocumentDatabase: Send + Sync {
  36. fn db_pool(&self) -> Result<Arc<ConnectionPool>, FlowyError>;
  37. }
  38. #[async_trait]
  39. pub trait DocumentEditor: Send + Sync {
  40. /// Called when the document get closed
  41. async fn close(&self);
  42. /// Exports the document content. The content is encoded in the corresponding
  43. /// editor data format.
  44. fn export(&self) -> FutureResult<String, FlowyError>;
  45. /// Duplicate the document inner data into String
  46. fn duplicate(&self) -> FutureResult<String, FlowyError>;
  47. fn receive_ws_data(&self, data: ServerRevisionWSData) -> FutureResult<(), FlowyError>;
  48. fn receive_ws_state(&self, state: &WSConnectState);
  49. /// Receives the local operations made by the user input. The operations are encoded
  50. /// in binary format.
  51. fn compose_local_operations(&self, data: Bytes) -> FutureResult<(), FlowyError>;
  52. /// Returns the `Any` reference that can be used to downcast back to the original,
  53. /// concrete type.
  54. ///
  55. /// The indirection through `as_any` is because using `downcast_ref`
  56. /// on `Box<A>` *directly* only lets us downcast back to `&A` again. You can take a look at [this](https://stackoverflow.com/questions/33687447/how-to-get-a-reference-to-a-concrete-type-from-a-trait-object)
  57. /// for more information.
  58. ///
  59. ///
  60. fn as_any(&self) -> &dyn Any;
  61. }
  62. #[derive(Clone, Debug)]
  63. pub struct DocumentConfig {
  64. pub version: DocumentVersionPB,
  65. }
  66. impl std::default::Default for DocumentConfig {
  67. fn default() -> Self {
  68. Self {
  69. version: DocumentVersionPB::V1,
  70. }
  71. }
  72. }
  73. pub struct DocumentManager {
  74. cloud_service: Arc<dyn DocumentCloudService>,
  75. rev_web_socket: Arc<dyn RevisionWebSocket>,
  76. editor_map: Arc<RwLock<RefCountHashMap<RefCountDocumentHandler>>>,
  77. user: Arc<dyn DocumentUser>,
  78. persistence: Arc<DocumentPersistence>,
  79. #[allow(dead_code)]
  80. config: DocumentConfig,
  81. }
  82. impl DocumentManager {
  83. pub fn new(
  84. cloud_service: Arc<dyn DocumentCloudService>,
  85. document_user: Arc<dyn DocumentUser>,
  86. database: Arc<dyn DocumentDatabase>,
  87. rev_web_socket: Arc<dyn RevisionWebSocket>,
  88. config: DocumentConfig,
  89. ) -> Self {
  90. Self {
  91. cloud_service,
  92. rev_web_socket,
  93. editor_map: Arc::new(RwLock::new(RefCountHashMap::new())),
  94. user: document_user,
  95. persistence: Arc::new(DocumentPersistence::new(database)),
  96. config,
  97. }
  98. }
  99. /// Called immediately after the application launched with the user sign in/sign up.
  100. #[tracing::instrument(level = "trace", skip_all, err)]
  101. pub async fn initialize(&self, user_id: &str) -> FlowyResult<()> {
  102. self.persistence.initialize(user_id)?;
  103. listen_ws_state_changed(self.rev_web_socket.clone(), self.editor_map.clone());
  104. Ok(())
  105. }
  106. pub async fn initialize_with_new_user(&self, _user_id: &str, _token: &str) -> FlowyResult<()> {
  107. Ok(())
  108. }
  109. #[tracing::instrument(level = "trace", skip_all, fields(document_id), err)]
  110. pub async fn open_document_editor<T: AsRef<str>>(
  111. &self,
  112. document_id: T,
  113. ) -> Result<Arc<dyn DocumentEditor>, FlowyError> {
  114. let document_id = document_id.as_ref();
  115. tracing::Span::current().record("document_id", document_id);
  116. self.init_document_editor(document_id).await
  117. }
  118. #[tracing::instrument(level = "trace", skip(self, editor_id), fields(editor_id), err)]
  119. pub async fn close_document_editor<T: AsRef<str>>(&self, editor_id: T) -> Result<(), FlowyError> {
  120. let editor_id = editor_id.as_ref();
  121. tracing::Span::current().record("editor_id", editor_id);
  122. self.editor_map.write().await.remove(editor_id).await;
  123. Ok(())
  124. }
  125. pub async fn apply_edit(&self, params: EditParams) -> FlowyResult<()> {
  126. let editor = self.get_document_editor(&params.doc_id).await?;
  127. editor.compose_local_operations(Bytes::from(params.operations)).await?;
  128. Ok(())
  129. }
  130. pub async fn create_document<T: AsRef<str>>(&self, doc_id: T, revisions: Vec<Revision>) -> FlowyResult<()> {
  131. let doc_id = doc_id.as_ref().to_owned();
  132. let db_pool = self.persistence.database.db_pool()?;
  133. // Maybe we could save the document to disk without creating the RevisionManager
  134. let rev_manager = self.make_rev_manager(&doc_id, db_pool)?;
  135. rev_manager.reset_object(revisions).await?;
  136. Ok(())
  137. }
  138. pub async fn receive_ws_data(&self, data: Bytes) {
  139. let result: Result<ServerRevisionWSData, serde_json::Error> = ServerRevisionWSData::try_from(data);
  140. match result {
  141. Ok(data) => match self.editor_map.read().await.get(&data.object_id) {
  142. None => tracing::error!(
  143. "Can't find any source handler for {:?}-{:?}",
  144. data.object_id,
  145. data.payload
  146. ),
  147. Some(handler) => match handler.0.receive_ws_data(data).await {
  148. Ok(_) => {}
  149. Err(e) => tracing::error!("{}", e),
  150. },
  151. },
  152. Err(e) => {
  153. tracing::error!("Document ws data parser failed: {:?}", e);
  154. }
  155. }
  156. }
  157. pub fn initial_document_content(&self) -> String {
  158. match self.config.version {
  159. DocumentVersionPB::V0 => initial_delta_document_content(),
  160. DocumentVersionPB::V1 => initial_document_content(),
  161. }
  162. }
  163. }
  164. impl DocumentManager {
  165. /// Returns the `DocumentEditor`
  166. ///
  167. /// # Arguments
  168. ///
  169. /// * `doc_id`: the id of the document
  170. ///
  171. /// returns: Result<Arc<DocumentEditor>, FlowyError>
  172. ///
  173. async fn get_document_editor(&self, doc_id: &str) -> FlowyResult<Arc<dyn DocumentEditor>> {
  174. match self.editor_map.read().await.get(doc_id) {
  175. None => {
  176. //
  177. tracing::warn!("Should call init_document_editor first");
  178. self.init_document_editor(doc_id).await
  179. }
  180. Some(handler) => Ok(handler.0.clone()),
  181. }
  182. }
  183. /// Initializes a document editor with the doc_id
  184. ///
  185. /// # Arguments
  186. ///
  187. /// * `doc_id`: the id of the document
  188. /// * `pool`: sqlite connection pool
  189. ///
  190. /// returns: Result<Arc<DocumentEditor>, FlowyError>
  191. ///
  192. #[tracing::instrument(level = "trace", skip(self), err)]
  193. pub async fn init_document_editor(&self, doc_id: &str) -> Result<Arc<dyn DocumentEditor>, FlowyError> {
  194. let pool = self.persistence.database.db_pool()?;
  195. let user = self.user.clone();
  196. let token = self.user.token()?;
  197. let cloud_service = Arc::new(DocumentRevisionCloudService {
  198. token,
  199. server: self.cloud_service.clone(),
  200. });
  201. match self.config.version {
  202. DocumentVersionPB::V0 => {
  203. let rev_manager = self.make_delta_document_rev_manager(doc_id, pool.clone())?;
  204. let editor: Arc<dyn DocumentEditor> = Arc::new(
  205. DeltaDocumentEditor::new(doc_id, user, rev_manager, self.rev_web_socket.clone(), cloud_service)
  206. .await?,
  207. );
  208. self.editor_map
  209. .write()
  210. .await
  211. .insert(doc_id.to_string(), RefCountDocumentHandler(editor.clone()));
  212. Ok(editor)
  213. }
  214. DocumentVersionPB::V1 => {
  215. let rev_manager = self.make_document_rev_manager(doc_id, pool.clone())?;
  216. let editor: Arc<dyn DocumentEditor> =
  217. Arc::new(AppFlowyDocumentEditor::new(doc_id, user, rev_manager, cloud_service).await?);
  218. self.editor_map
  219. .write()
  220. .await
  221. .insert(doc_id.to_string(), RefCountDocumentHandler(editor.clone()));
  222. Ok(editor)
  223. }
  224. }
  225. }
  226. fn make_rev_manager(
  227. &self,
  228. doc_id: &str,
  229. pool: Arc<ConnectionPool>,
  230. ) -> Result<RevisionManager<Arc<ConnectionPool>>, FlowyError> {
  231. match self.config.version {
  232. DocumentVersionPB::V0 => self.make_delta_document_rev_manager(doc_id, pool),
  233. DocumentVersionPB::V1 => self.make_document_rev_manager(doc_id, pool),
  234. }
  235. }
  236. fn make_document_rev_manager(
  237. &self,
  238. doc_id: &str,
  239. pool: Arc<ConnectionPool>,
  240. ) -> Result<RevisionManager<Arc<ConnectionPool>>, FlowyError> {
  241. let user_id = self.user.user_id()?;
  242. let disk_cache = SQLiteDocumentRevisionPersistence::new(&user_id, pool.clone());
  243. let configuration = RevisionPersistenceConfiguration::new(200, true);
  244. let rev_persistence = RevisionPersistence::new(&user_id, doc_id, disk_cache, configuration);
  245. let snapshot_persistence = SQLiteDocumentRevisionSnapshotPersistence::new(doc_id, pool);
  246. Ok(RevisionManager::new(
  247. &user_id,
  248. doc_id,
  249. rev_persistence,
  250. DocumentRevisionMergeable(),
  251. snapshot_persistence,
  252. ))
  253. }
  254. fn make_delta_document_rev_manager(
  255. &self,
  256. doc_id: &str,
  257. pool: Arc<ConnectionPool>,
  258. ) -> Result<RevisionManager<Arc<ConnectionPool>>, FlowyError> {
  259. let user_id = self.user.user_id()?;
  260. let disk_cache = SQLiteDeltaDocumentRevisionPersistence::new(&user_id, pool);
  261. let configuration = RevisionPersistenceConfiguration::new(100, true);
  262. let rev_persistence = RevisionPersistence::new(&user_id, doc_id, disk_cache, configuration);
  263. Ok(RevisionManager::new(
  264. &user_id,
  265. doc_id,
  266. rev_persistence,
  267. DeltaDocumentRevisionMergeable(),
  268. DeltaDocumentSnapshotPersistence(),
  269. ))
  270. }
  271. }
  272. struct DocumentRevisionCloudService {
  273. token: String,
  274. server: Arc<dyn DocumentCloudService>,
  275. }
  276. impl RevisionCloudService for DocumentRevisionCloudService {
  277. #[tracing::instrument(level = "trace", skip(self))]
  278. fn fetch_object(&self, user_id: &str, object_id: &str) -> FutureResult<Vec<Revision>, FlowyError> {
  279. let params: DocumentId = object_id.to_string().into();
  280. let server = self.server.clone();
  281. let token = self.token.clone();
  282. FutureResult::new(async move {
  283. match server.fetch_document(&token, params).await? {
  284. None => Err(FlowyError::record_not_found().context("Remote doesn't have this document")),
  285. Some(payload) => {
  286. let bytes = Bytes::from(payload.data.clone());
  287. let doc_md5 = md5(&bytes);
  288. let revision = Revision::new(&payload.doc_id, payload.base_rev_id, payload.rev_id, bytes, doc_md5);
  289. Ok(vec![revision])
  290. }
  291. }
  292. })
  293. }
  294. }
  295. #[derive(Clone)]
  296. struct RefCountDocumentHandler(Arc<dyn DocumentEditor>);
  297. #[async_trait]
  298. impl RefCountValue for RefCountDocumentHandler {
  299. async fn did_remove(&self) {
  300. self.0.close().await;
  301. }
  302. }
  303. impl std::ops::Deref for RefCountDocumentHandler {
  304. type Target = Arc<dyn DocumentEditor>;
  305. fn deref(&self) -> &Self::Target {
  306. &self.0
  307. }
  308. }
  309. #[tracing::instrument(level = "trace", skip(web_socket, handlers))]
  310. fn listen_ws_state_changed(
  311. web_socket: Arc<dyn RevisionWebSocket>,
  312. handlers: Arc<RwLock<RefCountHashMap<RefCountDocumentHandler>>>,
  313. ) {
  314. tokio::spawn(async move {
  315. let mut notify = web_socket.subscribe_state_changed().await;
  316. while let Ok(state) = notify.recv().await {
  317. handlers.read().await.values().iter().for_each(|handler| {
  318. handler.receive_ws_state(&state);
  319. })
  320. }
  321. });
  322. }