manager.rs 12 KB

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