refactor: try merge update before output and after input

This commit is contained in:
linonetwo
2023-02-07 01:32:51 +08:00
parent 765cd983fc
commit dc72b2ea11
+26 -40
View File
@@ -52,13 +52,27 @@ pub async fn get_doc<'s>(
parameters: GetDocumentParameter,
) -> Result<GetDocumentResponse, String> {
// TODO: check user permission
let state = &state.0.lock().await;
let doc_store = &state.doc_store;
let doc_db = &state.doc_db;
if let Ok(all_updates_of_workspace) = &state.0.lock().await.doc_db.all(&parameters.id).await {
if let Ok(all_updates_of_workspace) = doc_db.all(&parameters.id).await {
let all_updates = all_updates_of_workspace
.iter()
.map(|model| model.blob.clone())
.collect::<Vec<Vec<u8>>>();
all_updates
.iter()
.for_each(|update_blob| {
let mut tx = doc_store.doc().transact();
let update = Update::decode_v1(&update_blob).unwrap();
tx.apply_update(update);
tx.commit();
});
let merged_update = doc_store.doc().transact().encode_update_v1();
// TODO: store merged update here
Ok(GetDocumentResponse {
updates: all_updates_of_workspace
.iter()
.map(|model| model.blob.clone())
.collect::<Vec<Vec<u8>>>(),
updates: vec![merged_update],
})
} else {
Err(format!(
@@ -75,43 +89,15 @@ pub async fn update_y_document<'s>(
) -> Result<bool, String> {
let state = &state.0.lock().await;
let doc_store = &state.doc_store;
let doc_db = &state.doc_db;
let mut tx = doc_store.doc().transact();
let update = Update::decode_v1(&parameters.update).unwrap();
let mut decoder = DecoderV1::from(&parameters.update[..]);
for msg in MessageReader::new(&mut decoder) {
msg.ok().and_then(|msg| match msg {
Message::Sync(msg) => match msg {
SyncMessage::SyncStep1(sv) => {
Some(())
}
SyncMessage::SyncStep2(update) => {
Some(())
}
SyncMessage::Update(update) => {
let mut tx = doc_store.doc().transact();
tx.apply_update(Update::decode_v1(&update).unwrap());
tx.commit();
let merged_update = tx.encode_update_v1();
Some(())
}
},
Message::Auth(reason) => {
Some(())
}
Message::AwarenessQuery => {
Some(())
}
Message::Awareness(update) => {
Some(())
}
Message::Custom(tag, data) => {
Some(())
}
});
}
let merged_update = doc_store.doc().transact().encode_update_v1();
tx.apply_update(update);
let merged_update = tx.encode_update_v1();
tx.commit();
let doc_db = &state.doc_db;
doc_db
.insert(&parameters.id.clone(), &merged_update)
.replace_with(&parameters.id.clone(), merged_update)
.await
.ok();