manager.rs 13 KB

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