operation.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. use crate::core::{Body, Changeset, NodeData, OperationTransform, Path};
  2. use crate::errors::OTError;
  3. use serde::{Deserialize, Serialize};
  4. use std::sync::Arc;
  5. #[derive(Debug, Clone, Serialize, Deserialize)]
  6. #[serde(tag = "op")]
  7. pub enum NodeOperation {
  8. #[serde(rename = "insert")]
  9. Insert { path: Path, nodes: Vec<NodeData> },
  10. #[serde(rename = "update")]
  11. Update { path: Path, changeset: Changeset },
  12. #[serde(rename = "delete")]
  13. Delete { path: Path, nodes: Vec<NodeData> },
  14. }
  15. impl NodeOperation {
  16. pub fn get_path(&self) -> &Path {
  17. match self {
  18. NodeOperation::Insert { path, .. } => path,
  19. NodeOperation::Delete { path, .. } => path,
  20. NodeOperation::Update { path, .. } => path,
  21. }
  22. }
  23. pub fn get_mut_path(&mut self) -> &mut Path {
  24. match self {
  25. NodeOperation::Insert { path, .. } => path,
  26. NodeOperation::Delete { path, .. } => path,
  27. NodeOperation::Update { path, .. } => path,
  28. }
  29. }
  30. pub fn is_update_delta(&self) -> bool {
  31. match self {
  32. NodeOperation::Insert { .. } => false,
  33. NodeOperation::Update { path: _, changeset } => changeset.is_delta(),
  34. NodeOperation::Delete { .. } => false,
  35. }
  36. }
  37. pub fn is_update_attribute(&self) -> bool {
  38. match self {
  39. NodeOperation::Insert { .. } => false,
  40. NodeOperation::Update { path: _, changeset } => changeset.is_attribute(),
  41. NodeOperation::Delete { .. } => false,
  42. }
  43. }
  44. pub fn is_insert(&self) -> bool {
  45. match self {
  46. NodeOperation::Insert { .. } => true,
  47. NodeOperation::Update { .. } => false,
  48. NodeOperation::Delete { .. } => false,
  49. }
  50. }
  51. pub fn can_compose(&self, other: &NodeOperation) -> bool {
  52. if self.get_path() != other.get_path() {
  53. return false;
  54. }
  55. if self.is_update_delta() && other.is_update_delta() {
  56. return true;
  57. }
  58. if self.is_update_attribute() && other.is_update_attribute() {
  59. return true;
  60. }
  61. if self.is_insert() && other.is_update_delta() {
  62. return true;
  63. }
  64. false
  65. }
  66. pub fn compose(&mut self, other: &NodeOperation) -> Result<(), OTError> {
  67. match (self, other) {
  68. (
  69. NodeOperation::Insert { path: _, nodes },
  70. NodeOperation::Update {
  71. path: _other_path,
  72. changeset,
  73. },
  74. ) => {
  75. match changeset {
  76. Changeset::Delta { delta, inverted: _ } => {
  77. if let Body::Delta(old_delta) = &mut nodes.last_mut().unwrap().body {
  78. let new_delta = old_delta.compose(delta)?;
  79. *old_delta = new_delta;
  80. }
  81. },
  82. Changeset::Attributes { new: _, old: _ } => {
  83. return Err(OTError::compose().context("Can't compose the attributes changeset"));
  84. },
  85. }
  86. Ok(())
  87. },
  88. (
  89. NodeOperation::Update { path: _, changeset },
  90. NodeOperation::Update {
  91. path: _,
  92. changeset: other_changeset,
  93. },
  94. ) => changeset.compose(other_changeset),
  95. (_left, _right) => Err(OTError::compose().context("Can't compose the operation")),
  96. }
  97. }
  98. pub fn inverted(&self) -> NodeOperation {
  99. match self {
  100. NodeOperation::Insert { path, nodes } => NodeOperation::Delete {
  101. path: path.clone(),
  102. nodes: nodes.clone(),
  103. },
  104. NodeOperation::Delete { path, nodes } => NodeOperation::Insert {
  105. path: path.clone(),
  106. nodes: nodes.clone(),
  107. },
  108. NodeOperation::Update {
  109. path,
  110. changeset: body,
  111. } => NodeOperation::Update {
  112. path: path.clone(),
  113. changeset: body.inverted(),
  114. },
  115. }
  116. }
  117. /// Make the `other` operation can be applied to the version after applying the `self` operation.
  118. /// The semantics of transform is used when editing conflicts occur, which is often determined by the version id。
  119. /// For example, if the inserted position has been acquired by others, then it's needed to do the transform to
  120. /// make sure the inserted position is right.
  121. ///
  122. /// # Arguments
  123. ///
  124. /// * `other`: The operation that is going to be transformed
  125. ///
  126. /// # Examples
  127. ///
  128. /// ```
  129. /// use lib_ot::core::{NodeDataBuilder, NodeOperation, Path};
  130. /// let node_1 = NodeDataBuilder::new("text_1").build();
  131. /// let node_2 = NodeDataBuilder::new("text_2").build();
  132. ///
  133. /// let op_1 = NodeOperation::Insert {
  134. /// path: Path(vec![0, 1]),
  135. /// nodes: vec![node_1],
  136. /// };
  137. ///
  138. /// let mut op_2 = NodeOperation::Insert {
  139. /// path: Path(vec![0, 1]),
  140. /// nodes: vec![node_2],
  141. /// };
  142. ///
  143. /// assert_eq!(serde_json::to_string(&op_2).unwrap(), r#"{"op":"insert","path":[0,1],"nodes":[{"type":"text_2"}]}"#);
  144. ///
  145. /// op_1.transform(&mut op_2);
  146. /// assert_eq!(serde_json::to_string(&op_2).unwrap(), r#"{"op":"insert","path":[0,2],"nodes":[{"type":"text_2"}]}"#);
  147. /// assert_eq!(serde_json::to_string(&op_1).unwrap(), r#"{"op":"insert","path":[0,1],"nodes":[{"type":"text_1"}]}"#);
  148. /// ```
  149. pub fn transform(&self, other: &mut NodeOperation) {
  150. match self {
  151. NodeOperation::Insert { path, nodes } => {
  152. let new_path = path.transform(other.get_path(), nodes.len());
  153. *other.get_mut_path() = new_path;
  154. },
  155. NodeOperation::Delete { path, nodes } => {
  156. let new_path = path.transform(other.get_path(), nodes.len());
  157. *other.get_mut_path() = new_path;
  158. },
  159. _ => {
  160. // Only insert/delete will change the path.
  161. },
  162. }
  163. }
  164. }
  165. type OperationIndexMap = Vec<Arc<NodeOperation>>;
  166. #[derive(Debug, Clone, Default)]
  167. pub struct NodeOperations {
  168. inner: OperationIndexMap,
  169. }
  170. impl NodeOperations {
  171. pub fn new() -> Self {
  172. Self::default()
  173. }
  174. pub fn from_operations(operations: Vec<NodeOperation>) -> Self {
  175. let mut ops = Self::new();
  176. for op in operations {
  177. ops.push_op(op)
  178. }
  179. ops
  180. }
  181. pub fn from_bytes(bytes: Vec<u8>) -> Result<Self, OTError> {
  182. let operation_list =
  183. serde_json::from_slice(&bytes).map_err(|err| OTError::serde().context(err))?;
  184. Ok(operation_list)
  185. }
  186. pub fn to_bytes(&self) -> Result<Vec<u8>, OTError> {
  187. let bytes = serde_json::to_vec(self).map_err(|err| OTError::serde().context(err))?;
  188. Ok(bytes)
  189. }
  190. pub fn values(&self) -> &Vec<Arc<NodeOperation>> {
  191. &self.inner
  192. }
  193. pub fn values_mut(&mut self) -> &mut Vec<Arc<NodeOperation>> {
  194. &mut self.inner
  195. }
  196. pub fn len(&self) -> usize {
  197. self.values().len()
  198. }
  199. pub fn is_empty(&self) -> bool {
  200. self.inner.is_empty()
  201. }
  202. pub fn into_inner(self) -> Vec<Arc<NodeOperation>> {
  203. self.inner
  204. }
  205. pub fn push_op<T: Into<Arc<NodeOperation>>>(&mut self, other: T) {
  206. let other = other.into();
  207. if let Some(last_operation) = self.inner.last_mut() {
  208. if last_operation.can_compose(&other) {
  209. let mut_operation = Arc::make_mut(last_operation);
  210. if mut_operation.compose(&other).is_ok() {
  211. return;
  212. }
  213. }
  214. }
  215. // If the passed-in operation can't be composed, then append it to the end.
  216. self.inner.push(other);
  217. }
  218. pub fn compose(&mut self, other: NodeOperations) {
  219. for operation in other.values() {
  220. self.push_op(operation.clone());
  221. }
  222. }
  223. pub fn inverted(&self) -> Self {
  224. let mut operations = Self::new();
  225. for operation in self.values() {
  226. operations.push_op(operation.inverted());
  227. }
  228. operations
  229. }
  230. }
  231. impl std::convert::From<Vec<NodeOperation>> for NodeOperations {
  232. fn from(operations: Vec<NodeOperation>) -> Self {
  233. Self::from_operations(operations)
  234. }
  235. }
  236. impl std::convert::From<NodeOperation> for NodeOperations {
  237. fn from(operation: NodeOperation) -> Self {
  238. Self::from_operations(vec![operation])
  239. }
  240. }