tree.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. use super::NodeOperations;
  2. use crate::core::{Changeset, Node, NodeData, NodeOperation, Path, Transaction};
  3. use crate::errors::{OTError, OTErrorCode};
  4. use indextree::{Arena, FollowingSiblings, NodeId};
  5. use std::sync::Arc;
  6. #[derive(Default, Debug, Clone)]
  7. pub struct NodeTreeContext {}
  8. #[derive(Debug, Clone)]
  9. pub struct NodeTree {
  10. arena: Arena<Node>,
  11. root: NodeId,
  12. pub context: NodeTreeContext,
  13. }
  14. impl Default for NodeTree {
  15. fn default() -> Self {
  16. Self::new(NodeTreeContext::default())
  17. }
  18. }
  19. pub const PLACEHOLDER_NODE_TYPE: &str = "";
  20. impl NodeTree {
  21. pub fn new(context: NodeTreeContext) -> NodeTree {
  22. let mut arena = Arena::new();
  23. let root = arena.new_node(Node::new("root"));
  24. NodeTree { arena, root, context }
  25. }
  26. pub fn from_node_data(node_data: NodeData, context: NodeTreeContext) -> Result<Self, OTError> {
  27. let mut tree = Self::new(context);
  28. tree.insert_nodes(&0_usize.into(), vec![node_data])?;
  29. Ok(tree)
  30. }
  31. pub fn from_bytes(bytes: &[u8]) -> Result<Self, OTError> {
  32. let tree: NodeTree = serde_json::from_slice(bytes).map_err(|e| OTError::serde().context(e))?;
  33. Ok(tree)
  34. }
  35. pub fn to_bytes(&self) -> Vec<u8> {
  36. match serde_json::to_vec(self) {
  37. Ok(bytes) => bytes,
  38. Err(e) => {
  39. tracing::error!("{}", e);
  40. vec![]
  41. }
  42. }
  43. }
  44. pub fn to_json(&self, pretty: bool) -> Result<String, OTError> {
  45. if pretty {
  46. match serde_json::to_string_pretty(self) {
  47. Ok(json) => Ok(json),
  48. Err(err) => Err(OTError::serde().context(err)),
  49. }
  50. } else {
  51. match serde_json::to_string(self) {
  52. Ok(json) => Ok(json),
  53. Err(err) => Err(OTError::serde().context(err)),
  54. }
  55. }
  56. }
  57. pub fn from_operations<T: Into<NodeOperations>>(operations: T, context: NodeTreeContext) -> Result<Self, OTError> {
  58. let operations = operations.into();
  59. let mut node_tree = NodeTree::new(context);
  60. for (_, operation) in operations.into_inner().into_iter().enumerate() {
  61. node_tree.apply_op(operation)?;
  62. }
  63. Ok(node_tree)
  64. }
  65. pub fn from_transaction<T: Into<Transaction>>(transaction: T, context: NodeTreeContext) -> Result<Self, OTError> {
  66. let transaction = transaction.into();
  67. let mut tree = Self::new(context);
  68. tree.apply_transaction(transaction)?;
  69. Ok(tree)
  70. }
  71. pub fn get_node(&self, node_id: NodeId) -> Option<&Node> {
  72. if node_id.is_removed(&self.arena) {
  73. return None;
  74. }
  75. Some(self.arena.get(node_id)?.get())
  76. }
  77. pub fn get_node_at_path(&self, path: &Path) -> Option<&Node> {
  78. let node_id = self.node_id_at_path(path)?;
  79. self.get_node(node_id)
  80. }
  81. pub fn get_node_data_at_path(&self, path: &Path) -> Option<NodeData> {
  82. let node_id = self.node_id_at_path(path)?;
  83. let node_data = self.get_node_data(node_id)?;
  84. Some(node_data)
  85. }
  86. pub fn get_node_data_at_root(&self) -> Option<NodeData> {
  87. self.get_node_data(self.root)
  88. }
  89. pub fn get_node_data(&self, node_id: NodeId) -> Option<NodeData> {
  90. let Node {
  91. node_type,
  92. body,
  93. attributes,
  94. } = self.get_node(node_id)?.clone();
  95. let mut node_data = NodeData::new(node_type);
  96. for (key, value) in attributes.into_inner() {
  97. node_data.attributes.insert(key, value);
  98. }
  99. node_data.body = body;
  100. let children = self.get_children_ids(node_id);
  101. for child in children.into_iter() {
  102. if let Some(child_node_data) = self.get_node_data(child) {
  103. node_data.children.push(child_node_data);
  104. }
  105. }
  106. Some(node_data)
  107. }
  108. pub fn root_node_id(&self) -> NodeId {
  109. self.root
  110. }
  111. pub fn get_children(&self, node_id: NodeId) -> Vec<&Node> {
  112. node_id
  113. .children(&self.arena)
  114. .flat_map(|node_id| self.get_node(node_id))
  115. .collect()
  116. }
  117. /// Returns a iterator used to iterate over the node ids whose parent node id is node_id
  118. ///
  119. /// * `node_id`: the children's parent node id
  120. ///
  121. pub fn get_children_ids(&self, node_id: NodeId) -> Vec<NodeId> {
  122. node_id.children(&self.arena).collect()
  123. }
  124. /// Serialize the node to JSON with node_id
  125. pub fn serialize_node(&self, node_id: NodeId, pretty_json: bool) -> Result<String, OTError> {
  126. let node_data = self
  127. .get_node_data(node_id)
  128. .ok_or_else(|| OTError::internal().context("Node doesn't exist exist"))?;
  129. if pretty_json {
  130. serde_json::to_string_pretty(&node_data).map_err(|err| OTError::serde().context(err))
  131. } else {
  132. serde_json::to_string(&node_data).map_err(|err| OTError::serde().context(err))
  133. }
  134. }
  135. ///
  136. /// # Examples
  137. ///
  138. /// ```
  139. /// use std::sync::Arc;
  140. /// use lib_ot::core::{NodeOperation, NodeTree, NodeData, Path};
  141. /// let nodes = vec![NodeData::new("text".to_string())];
  142. /// let root_path: Path = vec![0].into();
  143. /// let op = NodeOperation::Insert {path: root_path.clone(),nodes };
  144. ///
  145. /// let mut node_tree = NodeTree::default();
  146. /// node_tree.apply_op(Arc::new(op)).unwrap();
  147. /// let node_id = node_tree.node_id_at_path(&root_path).unwrap();
  148. /// let node_path = node_tree.path_from_node_id(node_id);
  149. /// debug_assert_eq!(node_path, root_path);
  150. /// ```
  151. pub fn node_id_at_path<T: Into<Path>>(&self, path: T) -> Option<NodeId> {
  152. let path = path.into();
  153. if !path.is_valid() {
  154. return None;
  155. }
  156. let mut node_id = self.root;
  157. for id in path.iter() {
  158. node_id = self.node_id_from_parent_at_index(node_id, *id)?;
  159. }
  160. if node_id.is_removed(&self.arena) {
  161. return None;
  162. }
  163. Some(node_id)
  164. }
  165. pub fn path_from_node_id(&self, node_id: NodeId) -> Path {
  166. let mut path = vec![];
  167. let mut current_node = node_id;
  168. // Use .skip(1) on the ancestors iterator to skip the root node.
  169. let ancestors = node_id.ancestors(&self.arena).skip(1);
  170. for parent_node in ancestors {
  171. let counter = self.index_of_node(parent_node, current_node);
  172. path.push(counter);
  173. current_node = parent_node;
  174. }
  175. path.reverse();
  176. Path(path)
  177. }
  178. fn index_of_node(&self, parent_node: NodeId, child_node: NodeId) -> usize {
  179. let mut counter: usize = 0;
  180. let iter = parent_node.children(&self.arena);
  181. for node in iter {
  182. if node == child_node {
  183. return counter;
  184. }
  185. counter += 1;
  186. }
  187. counter
  188. }
  189. /// Returns the note_id at the index of the tree which its id is note_id
  190. /// # Arguments
  191. ///
  192. /// * `node_id`: the node id of the child's parent
  193. /// * `index`: index of the node in parent children list
  194. ///
  195. /// returns: Option<NodeId>
  196. ///
  197. /// # Examples
  198. ///
  199. /// ```
  200. /// use std::sync::Arc;
  201. /// use lib_ot::core::{NodeOperation, NodeTree, NodeData, Path};
  202. /// let node_1 = NodeData::new("text".to_string());
  203. /// let inserted_path: Path = vec![0].into();
  204. ///
  205. /// let mut node_tree = NodeTree::default();
  206. /// let op = NodeOperation::Insert {path: inserted_path.clone(),nodes: vec![node_1.clone()] };
  207. /// node_tree.apply_op(Arc::new(op)).unwrap();
  208. ///
  209. /// let node_2 = node_tree.get_node_at_path(&inserted_path).unwrap();
  210. /// assert_eq!(node_2.node_type, node_1.node_type);
  211. /// ```
  212. pub fn node_id_from_parent_at_index(&self, node_id: NodeId, index: usize) -> Option<NodeId> {
  213. let children = node_id.children(&self.arena);
  214. for (counter, child) in children.enumerate() {
  215. if counter == index {
  216. return Some(child);
  217. }
  218. }
  219. None
  220. }
  221. ///
  222. /// # Arguments
  223. ///
  224. /// * `node_id`: if the node_is is None, then will use root node_id.
  225. ///
  226. /// returns number of the children of the root node
  227. ///
  228. pub fn number_of_children(&self, node_id: Option<NodeId>) -> usize {
  229. match node_id {
  230. None => self.root.children(&self.arena).count(),
  231. Some(node_id) => node_id.children(&self.arena).count(),
  232. }
  233. }
  234. pub fn following_siblings(&self, node_id: NodeId) -> FollowingSiblings<'_, Node> {
  235. node_id.following_siblings(&self.arena)
  236. }
  237. pub fn apply_transaction(&mut self, transaction: Transaction) -> Result<(), OTError> {
  238. let operations = transaction.split().0;
  239. for operation in operations {
  240. self.apply_op(operation)?;
  241. }
  242. Ok(())
  243. }
  244. pub fn apply_op<T: Into<Arc<NodeOperation>>>(&mut self, op: T) -> Result<(), OTError> {
  245. let op = match Arc::try_unwrap(op.into()) {
  246. Ok(op) => op,
  247. Err(op) => op.as_ref().clone(),
  248. };
  249. match op {
  250. NodeOperation::Insert { path, nodes } => self.insert_nodes(&path, nodes),
  251. NodeOperation::Update { path, changeset } => self.update(&path, changeset),
  252. NodeOperation::Delete { path, nodes: _ } => self.delete_node(&path),
  253. }
  254. }
  255. /// Inserts nodes at given path
  256. /// root
  257. /// 0 - A
  258. /// 0 - A1
  259. /// 1 - B
  260. /// 0 - B1
  261. /// 1 - B2
  262. ///
  263. /// The path of each node will be:
  264. /// A: [0]
  265. /// A1: [0,0]
  266. /// B: [1]
  267. /// B1: [1,0]
  268. /// B2: [1,1]
  269. ///
  270. /// When inserting multiple nodes into the same path, each of them will be appended to the root
  271. /// node. For example. The path is [0] and the nodes are [A, B, C]. After inserting the nodes,
  272. /// the tree will be:
  273. /// root
  274. /// 0: A
  275. /// 1: B
  276. /// 2: C
  277. ///
  278. /// returns error if the path is empty
  279. ///
  280. fn insert_nodes(&mut self, path: &Path, nodes: Vec<NodeData>) -> Result<(), OTError> {
  281. if !path.is_valid() {
  282. return Err(OTErrorCode::InvalidPath.into());
  283. }
  284. let (parent_path, last_path) = path.split_at(path.0.len() - 1);
  285. let last_index = *last_path.first().unwrap();
  286. if parent_path.is_empty() {
  287. self.insert_nodes_at_index(self.root, last_index, nodes)
  288. } else {
  289. let parent_node = match self.node_id_at_path(parent_path) {
  290. None => self.create_adjacent_nodes_for_path(parent_path),
  291. Some(parent_node) => parent_node,
  292. };
  293. self.insert_nodes_at_index(parent_node, last_index, nodes)
  294. }
  295. }
  296. /// Create the adjacent nodes for the path
  297. ///
  298. /// It will create a corresponding node for each node on the path if it's not existing.
  299. /// If the path is not start from zero, it will create its siblings.
  300. ///
  301. /// Check out the operation_insert_test.rs for more examples.
  302. /// * operation_insert_node_when_its_parent_is_not_exist
  303. /// * operation_insert_node_when_multiple_parent_is_not_exist_test
  304. ///
  305. /// # Arguments
  306. ///
  307. /// * `path`: creates nodes for this path
  308. ///
  309. /// returns: NodeId
  310. ///
  311. fn create_adjacent_nodes_for_path<T: Into<Path>>(&mut self, path: T) -> NodeId {
  312. let path = path.into();
  313. let mut node_id = self.root;
  314. for id in path.iter() {
  315. match self.node_id_from_parent_at_index(node_id, *id) {
  316. None => {
  317. let num_of_children = node_id.children(&self.arena).count();
  318. if *id > num_of_children {
  319. for _ in 0..(*id - num_of_children) {
  320. let node: Node = placeholder_node().into();
  321. let sibling_node = self.arena.new_node(node);
  322. node_id.append(sibling_node, &mut self.arena);
  323. }
  324. }
  325. let node: Node = placeholder_node().into();
  326. let new_node_id = self.arena.new_node(node);
  327. node_id.append(new_node_id, &mut self.arena);
  328. node_id = new_node_id;
  329. }
  330. Some(next_node_id) => {
  331. node_id = next_node_id;
  332. }
  333. }
  334. }
  335. node_id
  336. }
  337. /// Inserts nodes before the node with node_id
  338. ///
  339. fn insert_nodes_before(&mut self, node_id: &NodeId, nodes: Vec<NodeData>) {
  340. if node_id.is_removed(&self.arena) {
  341. tracing::warn!("Node:{:?} is remove before insert", node_id);
  342. return;
  343. }
  344. for node in nodes {
  345. let (node, children) = node.split();
  346. let new_node_id = self.arena.new_node(node);
  347. node_id.insert_before(new_node_id, &mut self.arena);
  348. self.append_nodes(&new_node_id, children);
  349. }
  350. }
  351. fn insert_nodes_at_index(&mut self, parent: NodeId, index: usize, nodes: Vec<NodeData>) -> Result<(), OTError> {
  352. if index == 0 && parent.children(&self.arena).next().is_none() {
  353. self.append_nodes(&parent, nodes);
  354. return Ok(());
  355. }
  356. // Append the node to the end of the children list if index greater or equal to the
  357. // length of the children.
  358. let num_of_children = parent.children(&self.arena).count();
  359. if index >= num_of_children {
  360. let mut num_of_nodes_to_insert = index - num_of_children;
  361. while num_of_nodes_to_insert > 0 {
  362. self.append_nodes(&parent, vec![placeholder_node()]);
  363. num_of_nodes_to_insert -= 1;
  364. }
  365. self.append_nodes(&parent, nodes);
  366. return Ok(());
  367. }
  368. let node_to_insert = self
  369. .node_id_from_parent_at_index(parent, index)
  370. .ok_or_else(|| OTError::internal().context(format!("Can't find the node at {}", index)))?;
  371. self.insert_nodes_before(&node_to_insert, nodes);
  372. Ok(())
  373. }
  374. fn append_nodes(&mut self, parent: &NodeId, nodes: Vec<NodeData>) {
  375. for node in nodes {
  376. let (node, children) = node.split();
  377. let new_node_id = self.arena.new_node(node);
  378. parent.append(new_node_id, &mut self.arena);
  379. self.append_nodes(&new_node_id, children);
  380. }
  381. }
  382. /// Removes a node and its descendants from the tree
  383. fn delete_node(&mut self, path: &Path) -> Result<(), OTError> {
  384. if !path.is_valid() {
  385. return Err(OTErrorCode::InvalidPath.into());
  386. }
  387. match self.node_id_at_path(path) {
  388. None => tracing::warn!("Can't find any node at path: {:?}", path),
  389. Some(node) => {
  390. node.remove_subtree(&mut self.arena);
  391. }
  392. }
  393. Ok(())
  394. }
  395. /// Update the node at path with the `changeset`
  396. ///
  397. /// Do nothing if there is no node at the path.
  398. ///
  399. /// # Arguments
  400. ///
  401. /// * `path`: references to the node that will be applied with the changeset
  402. /// * `changeset`: the change that will be applied to the node
  403. ///
  404. /// returns: Result<(), OTError>
  405. fn update(&mut self, path: &Path, changeset: Changeset) -> Result<(), OTError> {
  406. match self.mut_node_at_path(path, |node| node.apply_changeset(changeset)) {
  407. Ok(_) => {}
  408. Err(err) => tracing::error!("{}", err),
  409. }
  410. Ok(())
  411. }
  412. fn mut_node_at_path<F>(&mut self, path: &Path, f: F) -> Result<(), OTError>
  413. where
  414. F: FnOnce(&mut Node) -> Result<(), OTError>,
  415. {
  416. if !path.is_valid() {
  417. return Err(OTErrorCode::InvalidPath.into());
  418. }
  419. let node_id = self.node_id_at_path(path).ok_or_else(|| {
  420. OTError::path_not_found().context(format!("Can't find the mutated node at path: {:?}", path))
  421. })?;
  422. match self.arena.get_mut(node_id) {
  423. None => tracing::warn!("The path: {:?} does not contain any nodes", path),
  424. Some(node) => {
  425. let node = node.get_mut();
  426. f(node)?;
  427. }
  428. }
  429. Ok(())
  430. }
  431. }
  432. pub fn placeholder_node() -> NodeData {
  433. NodeData::new(PLACEHOLDER_NODE_TYPE)
  434. }