269 lines
8.9 KiB
Rust
Raw Normal View History

2022-03-05 10:59:44 +08:00
use crate::manager::GridUser;
2022-03-04 21:26:32 +08:00
use crate::services::kv_persistence::{GridKVPersistence, KVTransaction};
2022-03-05 17:52:25 +08:00
use crate::services::stringify::stringify_deserialize;
2022-03-06 09:03:02 +08:00
2022-03-05 17:52:25 +08:00
use dashmap::DashMap;
2022-03-04 18:11:12 +08:00
use flowy_collaboration::client_grid::{GridChange, GridPad};
use flowy_collaboration::entities::revision::Revision;
use flowy_collaboration::util::make_delta_from_revisions;
use flowy_error::{FlowyError, FlowyResult};
2022-03-05 17:52:25 +08:00
use flowy_grid_data_model::entities::{
2022-03-06 09:03:02 +08:00
Cell, Field, Grid, RawCell, RawRow, RepeatedField, RepeatedFieldOrder, RepeatedRow, RepeatedRowOrder, Row,
2022-03-04 18:11:12 +08:00
};
2022-03-06 09:03:02 +08:00
use flowy_sync::{RevisionCloudService, RevisionCompact, RevisionManager, RevisionObjectBuilder};
2022-03-04 18:11:12 +08:00
use lib_infra::future::FutureResult;
2022-03-05 10:59:44 +08:00
use lib_infra::uuid;
2022-03-04 18:11:12 +08:00
use lib_ot::core::PlainTextAttributes;
2022-03-06 09:03:02 +08:00
2022-03-09 16:11:24 +08:00
use dashmap::mapref::one::Ref;
2022-03-05 17:52:25 +08:00
use rayon::iter::{IntoParallelIterator, ParallelIterator};
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>,
grid_pad: Arc<RwLock<GridPad>>,
2022-03-04 18:11:12 +08:00
rev_manager: Arc<RevisionManager>,
2022-03-05 10:59:44 +08:00
kv_persistence: Arc<GridKVPersistence>,
2022-03-05 17:52:25 +08:00
field_map: DashMap<String, Field>,
2022-03-09 16:11:24 +08:00
cell_map: DashMap<String, RawCell>,
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,
kv_persistence: Arc<GridKVPersistence>,
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-05 17:52:25 +08:00
let grid_pad = rev_manager.load::<GridPadBuilder, GridRevisionCompact>(cloud).await?;
2022-03-04 18:11:12 +08:00
let rev_manager = Arc::new(rev_manager);
2022-03-05 17:52:25 +08:00
let field_map = load_all_fields(&grid_pad, &kv_persistence).await?;
let grid_pad = Arc::new(RwLock::new(grid_pad));
2022-03-09 16:11:24 +08:00
let cell_map = DashMap::new();
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,
grid_pad,
2022-03-04 18:11:12 +08:00
rev_manager,
2022-03-05 10:59:44 +08:00
kv_persistence,
2022-03-05 17:52:25 +08:00
field_map,
2022-03-09 16:11:24 +08:00
cell_map,
2022-03-04 22:09:16 +08:00
}))
2022-03-04 18:11:12 +08:00
}
2022-03-05 10:59:44 +08:00
pub async fn create_empty_row(&self) -> FlowyResult<()> {
2022-03-08 15:25:56 +08:00
let row = RawRow::new(&uuid(), &self.grid_id, vec![]);
2022-03-09 16:11:24 +08:00
self.cell_map.insert(row.id.clone(), row.clone());
2022-03-05 10:59:44 +08:00
self.create_row(row).await?;
Ok(())
}
async fn create_row(&self, row: RawRow) -> FlowyResult<()> {
2022-03-04 21:26:32 +08:00
let _ = self.modify(|grid| Ok(grid.create_row(&row)?)).await?;
2022-03-09 16:11:24 +08:00
self.cell_map.insert(row.id.clone(), row.clone());
2022-03-05 10:59:44 +08:00
let _ = self.kv_persistence.set(row)?;
2022-03-04 18:11:12 +08:00
Ok(())
}
2022-03-04 21:26:32 +08:00
pub async fn delete_rows(&self, ids: Vec<String>) -> FlowyResult<()> {
let _ = self.modify(|grid| Ok(grid.delete_rows(&ids)?)).await?;
// let _ = self.kv.batch_delete(ids)?;
Ok(())
}
2022-03-09 16:11:24 +08:00
// pub async fn update_row(&self, cell: Cell) -> FlowyResult<()> {
// match self.cell_map.get(&cell.id) {
// None => Err(FlowyError::internal().context(format!("Can't find cell with id: {}", cell.id))),
// Some(raw_cell) => {}
// }
// }
2022-03-04 21:26:32 +08:00
pub async fn create_field(&mut self, field: Field) -> FlowyResult<()> {
let _ = self.modify(|grid| Ok(grid.create_field(&field)?)).await?;
2022-03-05 10:59:44 +08:00
let _ = self.kv_persistence.set(field)?;
2022-03-04 21:26:32 +08:00
Ok(())
}
pub async fn delete_field(&mut self, field_id: &str) -> FlowyResult<()> {
let _ = self.modify(|grid| Ok(grid.delete_field(field_id)?)).await?;
// let _ = self.kv.remove(field_id)?;
Ok(())
}
2022-03-05 17:52:25 +08:00
pub async fn get_rows(&self, row_orders: RepeatedRowOrder) -> FlowyResult<RepeatedRow> {
let ids = row_orders
.items
.into_iter()
.map(|row_order| row_order.row_id)
.collect::<Vec<_>>();
let raw_rows: Vec<RawRow> = self.kv_persistence.batch_get(ids)?;
let make_cell = |field_id: String, raw_cell: RawCell| {
let some_field = self.field_map.get(&field_id);
if some_field.is_none() {
tracing::error!("Can't find the field with {}", field_id);
return None;
}
2022-03-09 16:11:24 +08:00
self.cell_map.insert(raw_cell.id.clone(), raw_cell.clone());
2022-03-05 17:52:25 +08:00
let field = some_field.unwrap();
match stringify_deserialize(raw_cell.data, field.value()) {
Ok(content) => {
let cell = Cell {
id: raw_cell.id,
field_id: field_id.clone(),
content,
};
Some((field_id, cell))
}
Err(_) => None,
}
};
let rows = raw_rows
.into_par_iter()
.map(|raw_row| {
2022-03-08 15:25:56 +08:00
let mut row = Row {
id: raw_row.id.clone(),
cell_by_field_id: Default::default(),
height: raw_row.height,
};
2022-03-05 17:52:25 +08:00
row.cell_by_field_id = raw_row
.cell_by_field_id
.into_par_iter()
.flat_map(|(field_id, raw_cell)| make_cell(field_id, raw_cell))
.collect::<HashMap<String, Cell>>();
row
})
.collect::<Vec<Row>>();
Ok(rows.into())
}
pub async fn get_fields(&self, field_orders: RepeatedFieldOrder) -> FlowyResult<RepeatedField> {
let fields = field_orders
.iter()
.flat_map(|field_order| match self.field_map.get(&field_order.field_id) {
None => {
tracing::error!("Can't find the field with {}", field_order.field_id);
None
}
Some(field) => Some(field.value().clone()),
})
.collect::<Vec<Field>>();
Ok(fields.into())
}
2022-03-05 10:59:44 +08:00
pub async fn grid_data(&self) -> Grid {
self.grid_pad.read().await.grid_data()
}
2022-03-05 22:30:42 +08:00
pub async fn delta_str(&self) -> String {
self.grid_pad.read().await.delta_str()
}
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-05 10:59:44 +08:00
F: for<'a> FnOnce(&'a mut GridPad) -> FlowyResult<Option<GridChange>>,
2022-03-04 18:11:12 +08:00
{
2022-03-05 10:59:44 +08:00
let mut write_guard = self.grid_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(())
}
async fn apply_change(&self, change: GridChange) -> FlowyResult<()> {
let GridChange { 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();
let delta_data = delta.to_bytes();
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
.add_local_revision::<GridRevisionCompact>(&revision)
.await?;
Ok(())
}
}
2022-03-05 17:52:25 +08:00
async fn load_all_fields(
grid_pad: &GridPad,
kv_persistence: &Arc<GridKVPersistence>,
) -> FlowyResult<DashMap<String, Field>> {
let field_ids = grid_pad
.field_orders()
.iter()
.map(|field_order| field_order.field_id.clone())
.collect::<Vec<_>>();
let fields = kv_persistence.batch_get::<Field>(field_ids)?;
let map = DashMap::new();
for field in fields {
map.insert(field.id.clone(), field);
}
Ok(map)
}
2022-03-04 18:11:12 +08:00
struct GridPadBuilder();
impl RevisionObjectBuilder for GridPadBuilder {
type Output = GridPad;
2022-03-05 10:59:44 +08:00
fn build_object(object_id: &str, revisions: Vec<Revision>) -> FlowyResult<Self::Output> {
let pad = GridPad::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![]) })
}
}
struct GridRevisionCompact();
impl RevisionCompact for GridRevisionCompact {
fn compact_revisions(user_id: &str, object_id: &str, mut revisions: Vec<Revision>) -> FlowyResult<Revision> {
if revisions.is_empty() {
return Err(FlowyError::internal().context("Can't compact the empty folder's revisions"));
}
if revisions.len() == 1 {
return Ok(revisions.pop().unwrap());
}
let first_revision = revisions.first().unwrap();
let last_revision = revisions.last().unwrap();
let (base_rev_id, rev_id) = first_revision.pair_rev_id();
let md5 = last_revision.md5.clone();
let delta = make_delta_from_revisions::<PlainTextAttributes>(revisions)?;
let delta_data = delta.to_bytes();
Ok(Revision::new(object_id, base_rev_id, rev_id, delta_data, user_id, md5))
}
}