416 lines
15 KiB
Rust
Raw Normal View History

2022-03-24 17:09:05 +08:00
use crate::dart_notification::{send_dart_notification, GridNotification};
2022-03-05 10:59:44 +08:00
use crate::manager::GridUser;
2022-03-14 23:16:25 +08:00
use crate::services::block_meta_editor::GridBlockMetaEditorManager;
2022-03-26 20:27:32 +08:00
use crate::services::field::{type_option_json_str_from_bytes, FieldBuilder};
2022-03-24 17:09:05 +08:00
use crate::services::row::*;
2022-03-11 21:36:00 +08:00
use bytes::Bytes;
2022-03-27 09:35:10 +08:00
use flowy_error::{ErrorCode, FlowyError, FlowyResult};
2022-03-24 17:09:05 +08:00
use flowy_grid_data_model::entities::*;
use flowy_revision::{RevisionCloudService, RevisionCompactor, RevisionManager, RevisionObjectBuilder};
use flowy_sync::client_grid::{GridChangeset, GridMetaPad, TypeOptionDataDeserializer};
2022-03-19 16:52:28 +08:00
use flowy_sync::entities::revision::Revision;
use flowy_sync::errors::CollaborateResult;
2022-03-19 16:52:28 +08:00
use flowy_sync::util::make_delta_from_revisions;
2022-03-04 18:11:12 +08:00
use lib_infra::future::FutureResult;
2022-03-12 09:30:13 +08:00
use lib_ot::core::PlainTextAttributes;
2022-03-24 17:09:05 +08:00
use std::collections::HashMap;
2022-03-04 18:11:12 +08:00
use std::sync::Arc;
2022-03-05 10:59:44 +08:00
use tokio::sync::RwLock;
2022-03-04 18:11:12 +08:00
pub struct ClientGridEditor {
2022-03-04 22:09:16 +08:00
grid_id: String,
2022-03-05 10:59:44 +08:00
user: Arc<dyn GridUser>,
2022-03-17 17:25:43 +08:00
pad: Arc<RwLock<GridMetaPad>>,
2022-03-04 18:11:12 +08:00
rev_manager: Arc<RevisionManager>,
2022-03-11 21:36:00 +08:00
block_meta_manager: Arc<GridBlockMetaEditorManager>,
2022-03-04 18:11:12 +08:00
}
impl ClientGridEditor {
pub async fn new(
2022-03-04 22:09:16 +08:00
grid_id: &str,
2022-03-05 10:59:44 +08:00
user: Arc<dyn GridUser>,
mut rev_manager: RevisionManager,
2022-03-04 22:09:16 +08:00
) -> FlowyResult<Arc<Self>> {
2022-03-05 10:59:44 +08:00
let token = user.token()?;
let cloud = Arc::new(GridRevisionCloudService { token });
2022-03-12 21:06:15 +08:00
let grid_pad = rev_manager.load::<GridPadBuilder>(Some(cloud)).await?;
2022-03-04 18:11:12 +08:00
let rev_manager = Arc::new(rev_manager);
2022-03-17 17:25:43 +08:00
let pad = Arc::new(RwLock::new(grid_pad));
2022-03-12 09:30:13 +08:00
2022-03-17 17:25:43 +08:00
let block_meta_manager =
Arc::new(GridBlockMetaEditorManager::new(grid_id, &user, pad.read().await.get_blocks().clone()).await?);
2022-03-05 17:52:25 +08:00
2022-03-04 22:09:16 +08:00
Ok(Arc::new(Self {
2022-03-05 10:59:44 +08:00
grid_id: grid_id.to_owned(),
user,
2022-03-17 17:25:43 +08:00
pad,
2022-03-04 18:11:12 +08:00
rev_manager,
2022-03-11 21:36:00 +08:00
block_meta_manager,
2022-03-04 22:09:16 +08:00
}))
2022-03-04 18:11:12 +08:00
}
2022-03-25 20:55:56 +08:00
pub async fn create_field(&self, params: CreateFieldParams) -> FlowyResult<()> {
let CreateFieldParams {
field,
type_option_data,
start_field_id,
2022-03-31 22:51:46 +08:00
grid_id,
2022-03-25 20:55:56 +08:00
} = params;
2022-03-24 17:09:05 +08:00
2022-03-25 20:55:56 +08:00
let _ = self
2022-03-31 22:51:46 +08:00
.modify(|grid| {
if grid.contain_field(&field.id) {
let deserializer = TypeOptionChangesetDeserializer(field.field_type.clone());
2022-03-31 22:51:46 +08:00
let changeset = FieldChangesetParams {
field_id: field.id,
grid_id,
name: Some(field.name),
desc: Some(field.desc),
field_type: Some(field.field_type),
frozen: Some(field.frozen),
visibility: Some(field.visibility),
width: Some(field.width),
type_option_data: Some(type_option_data),
};
Ok(grid.update_field(changeset, deserializer)?)
2022-03-31 22:51:46 +08:00
} else {
let type_option_json = type_option_json_str_from_bytes(type_option_data, &field.field_type);
let field_meta = FieldMeta {
id: field.id,
name: field.name,
desc: field.desc,
field_type: field.field_type,
frozen: field.frozen,
visibility: field.visibility,
width: field.width,
type_option_json,
};
Ok(grid.create_field(field_meta, start_field_id)?)
}
})
2022-03-25 20:55:56 +08:00
.await?;
2022-03-16 21:19:51 +08:00
let _ = self.notify_did_update_fields().await?;
2022-03-04 21:26:32 +08:00
Ok(())
}
2022-03-25 20:55:56 +08:00
pub async fn default_field_meta(&self, field_type: &FieldType) -> FlowyResult<FieldMeta> {
2022-03-26 20:27:32 +08:00
let name = format!("Property {}", self.pad.read().await.fields().len() + 1);
let field_meta = FieldBuilder::from_field_type(field_type).name(&name).build();
2022-03-25 15:02:43 +08:00
Ok(field_meta)
2022-03-24 17:09:05 +08:00
}
pub async fn contain_field(&self, field_id: &str) -> bool {
self.pad.read().await.contain_field(field_id)
2022-03-15 19:00:28 +08:00
}
2022-03-27 09:35:10 +08:00
pub async fn update_field(&self, mut params: FieldChangesetParams) -> FlowyResult<()> {
let deserializer = match self.pad.read().await.get_field(&params.field_id) {
None => return Err(ErrorCode::FieldDoesNotExist.into()),
Some(field_meta) => TypeOptionChangesetDeserializer(field_meta.field_type.clone()),
};
2022-03-27 09:35:10 +08:00
let _ = self.modify(|grid| Ok(grid.update_field(params, deserializer)?)).await?;
let _ = self.notify_did_update_fields().await?;
2022-03-12 22:52:24 +08:00
Ok(())
}
2022-03-12 21:06:15 +08:00
pub async fn delete_field(&self, field_id: &str) -> FlowyResult<()> {
2022-03-04 21:26:32 +08:00
let _ = self.modify(|grid| Ok(grid.delete_field(field_id)?)).await?;
let _ = self.notify_did_update_fields().await?;
2022-03-04 21:26:32 +08:00
Ok(())
}
pub async fn switch_to_field_type(&self, field_id: &str, field_type: FieldType) -> FlowyResult<EditFieldContext> {
let _ = self.modify(|grid| Ok(grid.delete_field(field_id)?)).await?;
let _ = self.notify_did_update_fields().await?;
todo!()
}
2022-03-27 11:14:21 +08:00
pub async fn duplicate_field(&self, field_id: &str) -> FlowyResult<()> {
let _ = self.modify(|grid| Ok(grid.duplicate_field(field_id)?)).await?;
let _ = self.notify_did_update_fields().await?;
Ok(())
}
2022-03-31 22:51:46 +08:00
pub async fn get_field(&self, field_id: &str) -> FlowyResult<Option<FieldMeta>> {
match self.pad.read().await.get_field(field_id) {
None => Ok(None),
Some(field_meta) => Ok(Some(field_meta.clone())),
}
}
2022-03-17 17:25:43 +08:00
pub async fn create_block(&self, grid_block: GridBlockMeta) -> FlowyResult<()> {
2022-03-13 11:06:28 +08:00
let _ = self.modify(|grid| Ok(grid.create_block(grid_block)?)).await?;
Ok(())
}
2022-03-17 17:25:43 +08:00
pub async fn update_block(&self, changeset: GridBlockMetaChangeset) -> FlowyResult<()> {
2022-03-14 17:24:25 +08:00
let _ = self.modify(|grid| Ok(grid.update_block(changeset)?)).await?;
2022-03-13 11:06:28 +08:00
Ok(())
}
2022-03-18 21:04:01 +08:00
pub async fn create_row(&self, start_row_id: Option<String>) -> FlowyResult<RowOrder> {
2022-03-17 17:25:43 +08:00
let field_metas = self.pad.read().await.get_field_metas(None)?;
let block_id = self.block_id().await?;
// insert empty row below the row whose id is upper_row_id
2022-03-18 21:04:01 +08:00
let row_meta_ctx = CreateRowMetaBuilder::new(&field_metas).build();
let row_meta = make_row_meta_from_context(&block_id, row_meta_ctx);
let row_order = RowOrder::from(&row_meta);
// insert the row
let row_count = self
.block_meta_manager
2022-03-17 17:25:43 +08:00
.create_row(&block_id, row_meta, start_row_id)
.await?;
// update block row count
2022-03-17 17:25:43 +08:00
let changeset = GridBlockMetaChangeset::from_row_count(&block_id, row_count);
2022-03-14 17:24:25 +08:00
let _ = self.update_block(changeset).await?;
2022-03-18 21:04:01 +08:00
Ok(row_order)
2022-03-14 17:24:25 +08:00
}
2022-03-13 23:16:52 +08:00
2022-03-18 21:04:01 +08:00
pub async fn insert_rows(&self, contexts: Vec<CreateRowMetaPayload>) -> FlowyResult<Vec<RowOrder>> {
2022-03-17 17:25:43 +08:00
let block_id = self.block_id().await?;
2022-03-14 17:24:25 +08:00
let mut rows_by_block_id: HashMap<String, Vec<RowMeta>> = HashMap::new();
2022-03-18 21:04:01 +08:00
let mut row_orders = vec![];
2022-03-14 17:24:25 +08:00
for ctx in contexts {
2022-03-18 21:04:01 +08:00
let row_meta = make_row_meta_from_context(&block_id, ctx);
row_orders.push(RowOrder::from(&row_meta));
2022-03-14 17:24:25 +08:00
rows_by_block_id
.entry(block_id.clone())
2022-03-16 10:02:37 +08:00
.or_insert_with(Vec::new)
2022-03-14 17:24:25 +08:00
.push(row_meta);
}
2022-03-17 17:25:43 +08:00
let changesets = self.block_meta_manager.insert_row(rows_by_block_id).await?;
2022-03-14 17:24:25 +08:00
for changeset in changesets {
let _ = self.update_block(changeset).await?;
}
2022-03-18 21:04:01 +08:00
Ok(row_orders)
2022-03-11 21:36:00 +08:00
}
2022-03-05 17:52:25 +08:00
2022-03-14 17:24:25 +08:00
pub async fn update_row(&self, changeset: RowMetaChangeset) -> FlowyResult<()> {
self.block_meta_manager.update_row(changeset).await
}
2022-03-18 17:14:46 +08:00
pub async fn get_rows(&self, block_id: &str) -> FlowyResult<RepeatedRow> {
let block_ids = vec![block_id.to_owned()];
let mut block_meta_data_vec = self.get_block_meta_data_vec(Some(&block_ids)).await?;
debug_assert_eq!(block_meta_data_vec.len(), 1);
if block_meta_data_vec.len() == 1 {
let block_meta_data = block_meta_data_vec.pop().unwrap();
let field_metas = self.get_field_metas(None).await?;
let rows = make_rows_from_row_metas(&field_metas, &block_meta_data.row_metas);
Ok(rows.into())
} else {
Ok(vec![].into())
}
}
pub async fn get_row(&self, block_id: &str, row_id: &str) -> FlowyResult<Option<Row>> {
match self.block_meta_manager.get_row(block_id, row_id).await? {
None => Ok(None),
Some(row) => {
let field_metas = self.get_field_metas(None).await?;
let row_metas = vec![row];
let mut rows = make_rows_from_row_metas(&field_metas, &row_metas);
debug_assert!(rows.len() == 1);
Ok(rows.pop())
}
}
}
2022-03-14 17:24:25 +08:00
pub async fn update_cell(&self, changeset: CellMetaChangeset) -> FlowyResult<()> {
2022-03-16 10:02:37 +08:00
if let Some(cell_data) = changeset.data.as_ref() {
2022-03-17 17:25:43 +08:00
match self.pad.read().await.get_field(&changeset.field_id) {
2022-03-16 10:02:37 +08:00
None => {
return Err(FlowyError::internal()
.context(format!("Can not find the field with id: {}", &changeset.field_id)));
}
Some(field_meta) => {
let _ = serialize_cell_data(cell_data, field_meta)?;
}
}
}
2022-03-16 21:19:51 +08:00
let field_metas = self.get_field_metas(None).await?;
2022-03-14 17:24:25 +08:00
let row_changeset: RowMetaChangeset = changeset.into();
2022-03-16 21:19:51 +08:00
let _ = self
.block_meta_manager
.update_cells(&field_metas, row_changeset)
.await?;
Ok(())
2022-03-05 17:52:25 +08:00
}
2022-03-18 17:14:46 +08:00
pub async fn get_blocks(&self, block_ids: Option<Vec<String>>) -> FlowyResult<RepeatedGridBlock> {
let block_meta_data_vec = self.get_block_meta_data_vec(block_ids.as_ref()).await?;
match block_ids {
None => make_grid_blocks(block_meta_data_vec),
Some(block_ids) => make_grid_block_from_block_metas(&block_ids, block_meta_data_vec),
2022-03-14 17:24:25 +08:00
}
2022-03-13 23:16:52 +08:00
}
2022-03-18 17:14:46 +08:00
pub async fn get_block_metas(&self) -> FlowyResult<Vec<GridBlockMeta>> {
let grid_blocks = self.pad.read().await.get_blocks();
Ok(grid_blocks)
2022-03-14 17:24:25 +08:00
}
2022-03-13 11:06:28 +08:00
2022-03-18 21:04:01 +08:00
pub async fn delete_rows(&self, row_orders: Vec<RowOrder>) -> FlowyResult<()> {
let changesets = self.block_meta_manager.delete_rows(row_orders).await?;
2022-03-14 17:24:25 +08:00
for changeset in changesets {
let _ = self.update_block(changeset).await?;
}
2022-03-13 11:06:28 +08:00
Ok(())
2022-03-05 17:52:25 +08:00
}
2022-03-15 11:07:18 +08:00
pub async fn grid_data(&self) -> FlowyResult<Grid> {
2022-03-17 17:25:43 +08:00
let field_orders = self.pad.read().await.get_field_orders();
2022-03-18 17:14:46 +08:00
let block_orders = self
.pad
.read()
.await
.get_blocks()
.into_iter()
.map(|grid_block_meta| GridBlockOrder {
block_id: grid_block_meta.block_id,
})
.collect::<Vec<_>>();
2022-03-15 11:07:18 +08:00
Ok(Grid {
id: self.grid_id.clone(),
field_orders,
2022-03-18 17:14:46 +08:00
block_orders,
2022-03-15 11:07:18 +08:00
})
2022-03-11 21:36:00 +08:00
}
2022-03-15 11:07:18 +08:00
pub async fn get_field_metas(&self, field_orders: Option<RepeatedFieldOrder>) -> FlowyResult<Vec<FieldMeta>> {
2022-03-27 11:14:21 +08:00
let mut field_metas = self.pad.read().await.get_field_metas(field_orders)?;
field_metas.retain(|field_meta| field_meta.visibility);
Ok(field_metas)
2022-03-05 10:59:44 +08:00
}
2022-03-18 17:14:46 +08:00
pub async fn get_block_meta_data_vec(
&self,
block_ids: Option<&Vec<String>>,
) -> FlowyResult<Vec<GridBlockMetaData>> {
match block_ids {
None => {
let grid_blocks = self.pad.read().await.get_blocks();
let row_metas_per_block = self
.block_meta_manager
.get_block_meta_data_from_blocks(grid_blocks)
.await?;
Ok(row_metas_per_block)
}
Some(block_ids) => {
let row_metas_per_block = self
.block_meta_manager
.get_block_meta_data(block_ids.as_slice())
.await?;
Ok(row_metas_per_block)
}
}
2022-03-13 11:06:28 +08:00
}
2022-03-15 19:00:28 +08:00
pub async fn delta_bytes(&self) -> Bytes {
2022-03-17 17:25:43 +08:00
self.pad.read().await.delta_bytes()
2022-03-05 22:30:42 +08:00
}
2022-03-04 21:26:32 +08:00
async fn modify<F>(&self, f: F) -> FlowyResult<()>
2022-03-04 18:11:12 +08:00
where
2022-03-16 21:19:51 +08:00
F: for<'a> FnOnce(&'a mut GridMetaPad) -> FlowyResult<Option<GridChangeset>>,
2022-03-04 18:11:12 +08:00
{
2022-03-17 17:25:43 +08:00
let mut write_guard = self.pad.write().await;
2022-03-04 18:11:12 +08:00
match f(&mut *write_guard)? {
None => {}
Some(change) => {
let _ = self.apply_change(change).await?;
}
}
Ok(())
}
2022-03-16 21:19:51 +08:00
async fn apply_change(&self, change: GridChangeset) -> FlowyResult<()> {
let GridChangeset { delta, md5 } = change;
2022-03-05 10:59:44 +08:00
let user_id = self.user.user_id()?;
2022-03-04 18:11:12 +08:00
let (base_rev_id, rev_id) = self.rev_manager.next_rev_id_pair();
2022-03-15 19:00:28 +08:00
let delta_data = delta.to_delta_bytes();
2022-03-04 18:11:12 +08:00
let revision = Revision::new(
&self.rev_manager.object_id,
base_rev_id,
rev_id,
delta_data,
2022-03-05 10:59:44 +08:00
&user_id,
2022-03-04 18:11:12 +08:00
md5,
);
let _ = self
.rev_manager
2022-03-11 21:36:00 +08:00
.add_local_revision(&revision, Box::new(GridRevisionCompactor()))
2022-03-04 18:11:12 +08:00
.await?;
Ok(())
}
2022-03-14 17:24:25 +08:00
2022-03-17 17:25:43 +08:00
async fn block_id(&self) -> FlowyResult<String> {
match self.pad.read().await.get_blocks().last() {
2022-03-14 17:24:25 +08:00
None => Err(FlowyError::internal().context("There is no grid block in this grid")),
2022-03-17 17:25:43 +08:00
Some(grid_block) => Ok(grid_block.block_id.clone()),
2022-03-14 17:24:25 +08:00
}
}
2022-03-16 21:19:51 +08:00
async fn notify_did_update_fields(&self) -> FlowyResult<()> {
let field_metas = self.get_field_metas(None).await?;
let repeated_field: RepeatedField = field_metas.into_iter().map(Field::from).collect::<Vec<_>>().into();
send_dart_notification(&self.grid_id, GridNotification::DidUpdateFields)
2022-03-16 21:19:51 +08:00
.payload(repeated_field)
.send();
Ok(())
}
2022-03-04 18:11:12 +08:00
}
2022-03-12 21:06:15 +08:00
#[cfg(feature = "flowy_unit_test")]
impl ClientGridEditor {
pub fn rev_manager(&self) -> Arc<RevisionManager> {
self.rev_manager.clone()
}
}
pub struct GridPadBuilder();
2022-03-04 18:11:12 +08:00
impl RevisionObjectBuilder for GridPadBuilder {
2022-03-10 12:01:31 +08:00
type Output = GridMetaPad;
2022-03-04 18:11:12 +08:00
2022-03-05 10:59:44 +08:00
fn build_object(object_id: &str, revisions: Vec<Revision>) -> FlowyResult<Self::Output> {
2022-03-10 12:01:31 +08:00
let pad = GridMetaPad::from_revisions(object_id, revisions)?;
2022-03-04 18:11:12 +08:00
Ok(pad)
}
}
struct GridRevisionCloudService {
#[allow(dead_code)]
token: String,
}
impl RevisionCloudService for GridRevisionCloudService {
#[tracing::instrument(level = "trace", skip(self))]
fn fetch_object(&self, _user_id: &str, _object_id: &str) -> FutureResult<Vec<Revision>, FlowyError> {
FutureResult::new(async move { Ok(vec![]) })
}
}
2022-03-11 21:36:00 +08:00
struct GridRevisionCompactor();
impl RevisionCompactor for GridRevisionCompactor {
fn bytes_from_revisions(&self, revisions: Vec<Revision>) -> FlowyResult<Bytes> {
let delta = make_delta_from_revisions::<PlainTextAttributes>(revisions)?;
2022-03-15 19:00:28 +08:00
Ok(delta.to_delta_bytes())
2022-03-11 21:36:00 +08:00
}
}
struct TypeOptionChangesetDeserializer(FieldType);
impl TypeOptionDataDeserializer for TypeOptionChangesetDeserializer {
fn deserialize(&self, type_option_data: Vec<u8>) -> CollaborateResult<String> {
// The type_option_data is serialized by protobuf. But the type_option_data should be
// serialized by utf-8. So we must transform the data here.
let type_option_json = type_option_json_str_from_bytes(type_option_data, &self.0);
Ok(type_option_json)
}
}