AppFlowy/rust-lib/flowy-document/src/services/doc/doc_controller.rs

143 lines
4.5 KiB
Rust
Raw Normal View History

use std::sync::Arc;
use bytes::Bytes;
2021-10-04 09:47:21 +00:00
use crate::{
entities::doc::{Doc, DocDelta, DocIdentifier},
2021-10-06 07:23:38 +00:00
errors::{DocError, DocResult},
2021-09-11 06:26:30 +00:00
module::DocumentUser,
services::{
cache::DocCache,
doc::{
edit::{ClientEditDoc, EditDocWsHandler},
2021-10-07 12:46:29 +00:00
revision::RevisionServer,
},
server::Server,
ws::WsDocumentManager,
},
};
2021-10-06 07:23:38 +00:00
use flowy_database::ConnectionPool;
2021-10-05 06:37:45 +00:00
use flowy_infra::future::{wrap_future, FnFuture, ResultFuture};
2021-10-07 12:46:29 +00:00
2021-10-05 06:37:45 +00:00
use tokio::time::{interval, Duration};
2021-09-14 08:22:44 +00:00
pub(crate) struct DocController {
server: Server,
ws_manager: Arc<WsDocumentManager>,
cache: Arc<DocCache>,
user: Arc<dyn DocumentUser>,
}
impl DocController {
pub(crate) fn new(server: Server, user: Arc<dyn DocumentUser>, ws: Arc<WsDocumentManager>) -> Self {
let cache = Arc::new(DocCache::new());
2021-09-26 08:39:57 +00:00
let controller = Self {
server,
user,
ws_manager: ws,
2021-09-26 08:39:57 +00:00
cache: cache.clone(),
};
controller
}
2021-10-05 06:37:45 +00:00
pub(crate) fn init(&self) -> DocResult<()> {
self.ws_manager.init();
Ok(())
}
#[tracing::instrument(level = "debug", skip(self, pool), err)]
2021-09-26 08:39:57 +00:00
pub(crate) async fn open(
&self,
params: DocIdentifier,
2021-09-26 08:39:57 +00:00
pool: Arc<ConnectionPool>,
) -> Result<Arc<ClientEditDoc>, DocError> {
if self.cache.is_opened(&params.doc_id) == false {
let edit_ctx = self.make_edit_context(&params.doc_id, pool.clone()).await?;
return Ok(edit_ctx);
}
2021-09-23 05:15:35 +00:00
let edit_doc_ctx = self.cache.get(&params.doc_id)?;
Ok(edit_doc_ctx)
}
pub(crate) fn close(&self, doc_id: &str) -> Result<(), DocError> {
self.cache.remove(doc_id);
self.ws_manager.remove_handler(doc_id);
Ok(())
}
2021-10-06 07:23:38 +00:00
#[tracing::instrument(level = "debug", skip(self), err)]
pub(crate) fn delete(&self, params: DocIdentifier) -> Result<(), DocError> {
let doc_id = &params.doc_id;
self.cache.remove(doc_id);
self.ws_manager.remove_handler(doc_id);
Ok(())
}
2021-09-23 05:15:35 +00:00
// the delta's data that contains attributes with null value will be considered
// as None e.g.
// json : {"retain":7,"attributes":{"bold":null}}
// deserialize delta: [ {retain: 7, attributes: {Bold: AttributeValue(None)}} ]
#[tracing::instrument(level = "debug", skip(self, delta), err)]
2021-10-06 07:23:38 +00:00
pub(crate) async fn edit_doc(&self, delta: DocDelta) -> Result<DocDelta, DocError> {
2021-09-23 05:15:35 +00:00
let edit_doc_ctx = self.cache.get(&delta.doc_id)?;
let _ = edit_doc_ctx.compose_local_delta(Bytes::from(delta.data)).await?;
2021-10-06 07:23:38 +00:00
Ok(edit_doc_ctx.delta().await?)
2021-09-23 05:15:35 +00:00
}
}
impl DocController {
async fn make_edit_context(&self, doc_id: &str, pool: Arc<ConnectionPool>) -> Result<Arc<ClientEditDoc>, DocError> {
// Opti: require upgradable_read lock and then upgrade to write lock using
// RwLockUpgradableReadGuard::upgrade(xx) of ws
// let doc = self.read_doc(doc_id, pool.clone()).await?;
let ws = self.ws_manager.ws();
let token = self.user.token()?;
let user = self.user.clone();
let server = Arc::new(RevisionServerImpl {
token,
server: self.server.clone(),
});
let edit_ctx = Arc::new(ClientEditDoc::new(doc_id, pool, ws, server, user).await?);
let ws_handler = Arc::new(EditDocWsHandler(edit_ctx.clone()));
self.ws_manager.register_handler(doc_id, ws_handler);
self.cache.set(edit_ctx.clone());
Ok(edit_ctx)
}
2021-09-21 07:07:07 +00:00
}
2021-09-26 08:39:57 +00:00
struct RevisionServerImpl {
token: String,
server: Server,
}
impl RevisionServer for RevisionServerImpl {
2021-10-18 14:08:35 +00:00
#[tracing::instrument(level = "debug", skip(self))]
2021-10-06 07:23:38 +00:00
fn fetch_document_from_remote(&self, doc_id: &str) -> ResultFuture<Doc, DocError> {
let params = DocIdentifier {
doc_id: doc_id.to_string(),
};
let server = self.server.clone();
let token = self.token.clone();
ResultFuture::new(async move {
match server.read_doc(&token, params).await? {
None => Err(DocError::record_not_found().context("Remote doesn't have this document")),
2021-10-06 07:23:38 +00:00
Some(doc) => Ok(doc),
}
})
}
}
2021-09-26 08:39:57 +00:00
#[allow(dead_code)]
fn event_loop(_cache: Arc<DocCache>) -> FnFuture<()> {
let mut i = interval(Duration::from_secs(3));
wrap_future(async move {
loop {
// cache.all_docs().iter().for_each(|doc| doc.tick());
i.tick().await;
}
})
}