2022-11-08 13:13:28 +00:00
|
|
|
use crate::{errors::CollaborateError, util::*};
|
|
|
|
use flowy_http_model::revision::{RepeatedRevision, Revision, RevisionRange};
|
|
|
|
use flowy_http_model::ws_data::{ServerRevisionWSData, ServerRevisionWSDataBuilder};
|
2022-01-15 03:20:28 +00:00
|
|
|
use lib_infra::future::BoxResultFuture;
|
2022-10-10 03:56:48 +00:00
|
|
|
use lib_ot::core::{DeltaOperations, OperationAttributes};
|
2022-01-15 03:20:28 +00:00
|
|
|
use parking_lot::RwLock;
|
|
|
|
use serde::de::DeserializeOwned;
|
|
|
|
use std::{
|
|
|
|
cmp::Ordering,
|
|
|
|
fmt::Debug,
|
|
|
|
sync::{
|
|
|
|
atomic::{AtomicI64, Ordering::SeqCst},
|
|
|
|
Arc,
|
|
|
|
},
|
|
|
|
time::Duration,
|
|
|
|
};
|
|
|
|
|
2022-10-10 03:56:48 +00:00
|
|
|
pub type RevisionOperations<Attribute> = DeltaOperations<Attribute>;
|
|
|
|
|
|
|
|
pub trait RevisionOperations2<Attribute>: Send + Sync {
|
|
|
|
fn from_bytes<B: AsRef<[u8]>>(bytes: B) -> Result<Self, CollaborateError>
|
|
|
|
where
|
|
|
|
Self: Sized;
|
|
|
|
}
|
|
|
|
|
2022-01-15 03:20:28 +00:00
|
|
|
pub trait RevisionUser: Send + Sync + Debug {
|
|
|
|
fn user_id(&self) -> String;
|
|
|
|
fn receive(&self, resp: RevisionSyncResponse);
|
|
|
|
}
|
|
|
|
|
|
|
|
pub trait RevisionSyncPersistence: Send + Sync + 'static {
|
|
|
|
fn read_revisions(
|
|
|
|
&self,
|
|
|
|
object_id: &str,
|
|
|
|
rev_ids: Option<Vec<i64>>,
|
2022-07-19 05:07:30 +00:00
|
|
|
) -> BoxResultFuture<Vec<Revision>, CollaborateError>;
|
2022-01-15 03:20:28 +00:00
|
|
|
|
2022-07-19 05:07:30 +00:00
|
|
|
fn save_revisions(&self, repeated_revision: RepeatedRevision) -> BoxResultFuture<(), CollaborateError>;
|
2022-01-15 03:20:28 +00:00
|
|
|
|
|
|
|
fn reset_object(
|
|
|
|
&self,
|
|
|
|
object_id: &str,
|
2022-07-19 05:07:30 +00:00
|
|
|
repeated_revision: RepeatedRevision,
|
2022-01-15 03:20:28 +00:00
|
|
|
) -> BoxResultFuture<(), CollaborateError>;
|
|
|
|
}
|
|
|
|
|
2022-10-10 03:56:48 +00:00
|
|
|
pub trait RevisionSyncObject<Attribute: OperationAttributes>: Send + Sync + 'static {
|
|
|
|
fn object_id(&self) -> &str;
|
|
|
|
|
|
|
|
fn object_json(&self) -> String;
|
|
|
|
|
|
|
|
fn compose(&mut self, other: &RevisionOperations<Attribute>) -> Result<(), CollaborateError>;
|
|
|
|
|
|
|
|
fn transform(
|
|
|
|
&self,
|
|
|
|
other: &RevisionOperations<Attribute>,
|
|
|
|
) -> Result<(RevisionOperations<Attribute>, RevisionOperations<Attribute>), CollaborateError>;
|
|
|
|
|
|
|
|
fn set_operations(&mut self, operations: RevisionOperations<Attribute>);
|
2022-01-15 03:20:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub enum RevisionSyncResponse {
|
|
|
|
Pull(ServerRevisionWSData),
|
|
|
|
Push(ServerRevisionWSData),
|
|
|
|
Ack(ServerRevisionWSData),
|
|
|
|
}
|
|
|
|
|
2022-10-10 03:56:48 +00:00
|
|
|
pub struct RevisionSynchronizer<Attribute: OperationAttributes> {
|
2022-01-15 03:20:28 +00:00
|
|
|
object_id: String,
|
|
|
|
rev_id: AtomicI64,
|
2022-10-10 03:56:48 +00:00
|
|
|
object: Arc<RwLock<dyn RevisionSyncObject<Attribute>>>,
|
2022-01-15 03:20:28 +00:00
|
|
|
persistence: Arc<dyn RevisionSyncPersistence>,
|
|
|
|
}
|
|
|
|
|
2022-10-10 03:56:48 +00:00
|
|
|
impl<Attribute> RevisionSynchronizer<Attribute>
|
2022-01-15 03:20:28 +00:00
|
|
|
where
|
2022-10-10 03:56:48 +00:00
|
|
|
Attribute: OperationAttributes + DeserializeOwned + serde::Serialize + 'static,
|
2022-01-15 03:20:28 +00:00
|
|
|
{
|
2022-10-10 03:56:48 +00:00
|
|
|
pub fn new<S, P>(rev_id: i64, sync_object: S, persistence: P) -> RevisionSynchronizer<Attribute>
|
2022-01-15 03:20:28 +00:00
|
|
|
where
|
2022-10-10 03:56:48 +00:00
|
|
|
S: RevisionSyncObject<Attribute>,
|
2022-01-15 03:20:28 +00:00
|
|
|
P: RevisionSyncPersistence,
|
|
|
|
{
|
|
|
|
let object = Arc::new(RwLock::new(sync_object));
|
|
|
|
let persistence = Arc::new(persistence);
|
2022-10-10 03:56:48 +00:00
|
|
|
let object_id = object.read().object_id().to_owned();
|
2022-01-15 03:20:28 +00:00
|
|
|
RevisionSynchronizer {
|
|
|
|
object_id,
|
|
|
|
rev_id: AtomicI64::new(rev_id),
|
|
|
|
object,
|
|
|
|
persistence,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-06 03:28:24 +00:00
|
|
|
#[tracing::instrument(level = "trace", skip(self, user, repeated_revision), err)]
|
2022-01-15 03:20:28 +00:00
|
|
|
pub async fn sync_revisions(
|
|
|
|
&self,
|
|
|
|
user: Arc<dyn RevisionUser>,
|
2022-07-19 05:07:30 +00:00
|
|
|
repeated_revision: RepeatedRevision,
|
2022-01-15 03:20:28 +00:00
|
|
|
) -> Result<(), CollaborateError> {
|
2022-01-21 13:41:24 +00:00
|
|
|
let object_id = self.object_id.clone();
|
2022-07-19 05:07:30 +00:00
|
|
|
if repeated_revision.is_empty() {
|
2022-01-15 03:20:28 +00:00
|
|
|
// Return all the revisions to client
|
2022-01-21 13:41:24 +00:00
|
|
|
let revisions = self.persistence.read_revisions(&object_id, None).await?;
|
2022-07-19 05:07:30 +00:00
|
|
|
let repeated_revision = RepeatedRevision::from(revisions);
|
2022-01-21 13:41:24 +00:00
|
|
|
let data = ServerRevisionWSDataBuilder::build_push_message(&object_id, repeated_revision);
|
2022-01-15 03:20:28 +00:00
|
|
|
user.receive(RevisionSyncResponse::Push(data));
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
|
|
|
let server_base_rev_id = self.rev_id.load(SeqCst);
|
2022-07-19 05:07:30 +00:00
|
|
|
let first_revision = repeated_revision.first().unwrap().clone();
|
2022-01-15 03:20:28 +00:00
|
|
|
if self.is_applied_before(&first_revision, &self.persistence).await {
|
|
|
|
// Server has received this revision before, so ignore the following revisions
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
|
|
|
match server_base_rev_id.cmp(&first_revision.rev_id) {
|
|
|
|
Ordering::Less => {
|
|
|
|
let server_rev_id = next(server_base_rev_id);
|
|
|
|
if server_base_rev_id == first_revision.base_rev_id || server_rev_id == first_revision.rev_id {
|
|
|
|
// The rev is in the right order, just compose it.
|
2022-07-19 05:07:30 +00:00
|
|
|
for revision in repeated_revision.iter() {
|
2022-01-15 03:20:28 +00:00
|
|
|
let _ = self.compose_revision(revision)?;
|
|
|
|
}
|
|
|
|
let _ = self.persistence.save_revisions(repeated_revision).await?;
|
|
|
|
} else {
|
2022-10-10 03:56:48 +00:00
|
|
|
// The server ops is outdated, pull the missing revision from the client.
|
2022-01-15 03:20:28 +00:00
|
|
|
let range = RevisionRange {
|
|
|
|
start: server_rev_id,
|
|
|
|
end: first_revision.rev_id,
|
|
|
|
};
|
|
|
|
let msg = ServerRevisionWSDataBuilder::build_pull_message(&self.object_id, range);
|
|
|
|
user.receive(RevisionSyncResponse::Pull(msg));
|
|
|
|
}
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
Ordering::Equal => {
|
|
|
|
// Do nothing
|
2022-01-24 13:23:57 +00:00
|
|
|
tracing::trace!("Applied {} revision rev_id is the same as cur_rev_id", self.object_id);
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
Ordering::Greater => {
|
2022-10-10 03:56:48 +00:00
|
|
|
// The client ops is outdated. Transform the client revision ops and then
|
|
|
|
// send the prime ops to the client. Client should compose the this prime
|
|
|
|
// ops.
|
2022-01-15 03:20:28 +00:00
|
|
|
let from_rev_id = first_revision.rev_id;
|
|
|
|
let to_rev_id = server_base_rev_id;
|
|
|
|
let _ = self.push_revisions_to_user(user, from_rev_id, to_rev_id).await;
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tracing::instrument(level = "trace", skip(self, user), fields(server_rev_id), err)]
|
|
|
|
pub async fn pong(&self, user: Arc<dyn RevisionUser>, client_rev_id: i64) -> Result<(), CollaborateError> {
|
2022-01-21 13:41:24 +00:00
|
|
|
let object_id = self.object_id.clone();
|
2022-01-15 03:20:28 +00:00
|
|
|
let server_rev_id = self.rev_id();
|
|
|
|
tracing::Span::current().record("server_rev_id", &server_rev_id);
|
|
|
|
match server_rev_id.cmp(&client_rev_id) {
|
|
|
|
Ordering::Less => {
|
2022-02-26 09:28:23 +00:00
|
|
|
tracing::trace!("Client should not send ping and the server should pull the revisions from the client")
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-21 13:41:24 +00:00
|
|
|
Ordering::Equal => tracing::trace!("{} is up to date.", object_id),
|
2022-01-15 03:20:28 +00:00
|
|
|
Ordering::Greater => {
|
2022-10-10 03:56:48 +00:00
|
|
|
// The client ops is outdated. Transform the client revision ops and then
|
|
|
|
// send the prime ops to the client. Client should compose the this prime
|
|
|
|
// ops.
|
2022-01-15 03:20:28 +00:00
|
|
|
let from_rev_id = client_rev_id;
|
|
|
|
let to_rev_id = server_rev_id;
|
|
|
|
tracing::trace!("Push revisions to user");
|
|
|
|
let _ = self.push_revisions_to_user(user, from_rev_id, to_rev_id).await;
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-01-21 13:41:24 +00:00
|
|
|
#[tracing::instrument(level = "debug", skip(self, repeated_revision), fields(object_id), err)]
|
2022-07-19 05:07:30 +00:00
|
|
|
pub async fn reset(&self, repeated_revision: RepeatedRevision) -> Result<(), CollaborateError> {
|
2022-01-21 13:41:24 +00:00
|
|
|
let object_id = self.object_id.clone();
|
|
|
|
tracing::Span::current().record("object_id", &object_id.as_str());
|
2022-07-19 05:07:30 +00:00
|
|
|
let revisions: Vec<Revision> = repeated_revision.clone().into_inner();
|
2022-01-15 03:20:28 +00:00
|
|
|
let (_, rev_id) = pair_rev_id_from_revision_pbs(&revisions);
|
2022-10-10 03:56:48 +00:00
|
|
|
let operations = make_operations_from_revisions(revisions)?;
|
2022-01-21 13:41:24 +00:00
|
|
|
let _ = self.persistence.reset_object(&object_id, repeated_revision).await?;
|
2022-10-10 03:56:48 +00:00
|
|
|
self.object.write().set_operations(operations);
|
2022-01-15 03:20:28 +00:00
|
|
|
let _ = self.rev_id.fetch_update(SeqCst, SeqCst, |_e| Some(rev_id));
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-01-24 09:35:58 +00:00
|
|
|
pub fn object_json(&self) -> String {
|
2022-10-10 03:56:48 +00:00
|
|
|
self.object.read().object_json()
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
|
2022-07-19 05:07:30 +00:00
|
|
|
fn compose_revision(&self, revision: &Revision) -> Result<(), CollaborateError> {
|
2022-10-10 03:56:48 +00:00
|
|
|
let operations = RevisionOperations::<Attribute>::from_bytes(&revision.bytes)?;
|
|
|
|
let _ = self.compose_operations(operations)?;
|
2022-01-15 03:20:28 +00:00
|
|
|
let _ = self.rev_id.fetch_update(SeqCst, SeqCst, |_e| Some(revision.rev_id));
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tracing::instrument(level = "debug", skip(self, revision))]
|
2022-10-10 03:56:48 +00:00
|
|
|
fn transform_revision(
|
|
|
|
&self,
|
2022-11-08 13:13:28 +00:00
|
|
|
revision: &flowy_http_model::protobuf::Revision,
|
2022-10-10 03:56:48 +00:00
|
|
|
) -> Result<(RevisionOperations<Attribute>, RevisionOperations<Attribute>), CollaborateError> {
|
|
|
|
let client_operations = RevisionOperations::<Attribute>::from_bytes(&revision.bytes)?;
|
|
|
|
let result = self.object.read().transform(&client_operations)?;
|
2022-01-15 03:20:28 +00:00
|
|
|
Ok(result)
|
|
|
|
}
|
|
|
|
|
2022-10-10 03:56:48 +00:00
|
|
|
fn compose_operations(&self, operations: RevisionOperations<Attribute>) -> Result<(), CollaborateError> {
|
|
|
|
if operations.is_empty() {
|
|
|
|
log::warn!("Composed operations is empty");
|
2022-01-15 03:20:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
match self.object.try_write_for(Duration::from_millis(300)) {
|
2022-01-21 13:41:24 +00:00
|
|
|
None => log::error!("Failed to acquire write lock of object"),
|
2022-01-15 03:20:28 +00:00
|
|
|
Some(mut write_guard) => {
|
2022-10-10 03:56:48 +00:00
|
|
|
let _ = write_guard.compose(&operations)?;
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-01-24 09:35:58 +00:00
|
|
|
pub(crate) fn rev_id(&self) -> i64 {
|
|
|
|
self.rev_id.load(SeqCst)
|
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
|
2022-07-19 05:07:30 +00:00
|
|
|
async fn is_applied_before(&self, new_revision: &Revision, persistence: &Arc<dyn RevisionSyncPersistence>) -> bool {
|
2022-01-15 03:20:28 +00:00
|
|
|
let rev_ids = Some(vec![new_revision.rev_id]);
|
|
|
|
if let Ok(revisions) = persistence.read_revisions(&self.object_id, rev_ids).await {
|
|
|
|
if let Some(revision) = revisions.first() {
|
|
|
|
if revision.md5 == new_revision.md5 {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn push_revisions_to_user(&self, user: Arc<dyn RevisionUser>, from: i64, to: i64) {
|
|
|
|
let rev_ids: Vec<i64> = (from..=to).collect();
|
2022-01-21 13:41:24 +00:00
|
|
|
tracing::debug!("Push revision: {} -> {} to client", from, to);
|
|
|
|
match self
|
|
|
|
.persistence
|
|
|
|
.read_revisions(&self.object_id, Some(rev_ids.clone()))
|
|
|
|
.await
|
|
|
|
{
|
2022-01-15 03:20:28 +00:00
|
|
|
Ok(revisions) => {
|
2022-01-21 13:41:24 +00:00
|
|
|
if !rev_ids.is_empty() && revisions.is_empty() {
|
|
|
|
tracing::trace!("{}: can not read the revisions in range {:?}", self.object_id, rev_ids);
|
|
|
|
// assert_eq!(revisions.is_empty(), rev_ids.is_empty(),);
|
|
|
|
}
|
2022-07-19 05:07:30 +00:00
|
|
|
|
|
|
|
let repeated_revision = RepeatedRevision::from(revisions);
|
|
|
|
let data = ServerRevisionWSDataBuilder::build_push_message(&self.object_id, repeated_revision);
|
|
|
|
user.receive(RevisionSyncResponse::Push(data));
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
Err(e) => {
|
|
|
|
tracing::error!("{}", e);
|
2022-01-24 09:35:58 +00:00
|
|
|
}
|
2022-01-15 03:20:28 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2022-01-24 09:35:58 +00:00
|
|
|
fn next(rev_id: i64) -> i64 {
|
|
|
|
rev_id + 1
|
|
|
|
}
|