Debian Codegraph @

third_party/rust/dogear/src/tree.rs

raw
1 // Copyright 2018-2019 Mozilla
2
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::{
16 borrow::Cow,
17 cmp::Ordering,
18 collections::{HashMap, HashSet},
19 convert::{TryFrom, TryInto},
20 fmt, mem,
21 ops::Deref,
22 ptr,
23 };
24
25 use smallbitvec::SmallBitVec;
26
27 use crate::error::{Error, ErrorKind, Result};
28 use crate::guid::Guid;
29
30 /// The type for entry indices in the tree.
31 type Index = usize;
32
33 /// A complete, rooted bookmark tree with tombstones.
34 ///
35 /// The tree stores bookmark items in a vector, and uses indices in the vector
36 /// to identify parents and children. This makes traversal and lookup very
37 /// efficient. Retrieving a node's parent takes one indexing operation,
38 /// retrieving children takes one indexing operation per child, and retrieving
39 /// a node by random GUID takes one hash map lookup and one indexing operation.
40 #[derive(Debug)]
41 pub struct Tree {
42 entry_index_by_guid: HashMap<Guid, Index>,
43 entries: Vec<TreeEntry>,
44 deleted_guids: HashSet<Guid>,
45 problems: Problems,
46 }
47
48 impl Tree {
49 /// Returns a builder for a rooted tree.
50 pub fn with_root(root: Item) -> Builder {
51 let mut entry_index_by_guid = HashMap::new();
52 entry_index_by_guid.insert(root.guid.clone(), 0);
53
54 Builder {
55 entries: vec![BuilderEntry {
56 item: root,
57 content: None,
58 parent: BuilderEntryParent::Root,
59 children: Vec::new(),
60 }],
61 deleted_guids: HashSet::new(),
62 entry_index_by_guid,
63 reparent_orphans_to: None,
64 }
65 }
66
67 /// Returns the number of nodes in the tree.
68 #[inline]
69 pub fn size(&self) -> usize {
70 self.entries.len()
71 }
72
73 /// Returns the root node.
74 #[inline]
75 pub fn root(&self) -> Node<'_> {
76 Node(self, &self.entries[0])
77 }
78
79 /// Returns the set of all tombstoned GUIDs.
80 #[inline]
81 pub fn deletions(&self) -> &HashSet<Guid> {
82 &self.deleted_guids
83 }
84
85 /// Indicates if the GUID exists in the tree.
86 #[inline]
87 pub fn exists(&self, guid: &Guid) -> bool {
88 self.entry_index_by_guid.contains_key(guid)
89 }
90
91 /// Indicates if the GUID is known to be deleted. If `Tree::node_for_guid`
92 /// returns `None` and `Tree::is_deleted` returns `false`, the item doesn't
93 /// exist in the tree at all.
94 #[inline]
95 pub fn is_deleted(&self, guid: &Guid) -> bool {
96 self.deleted_guids.contains(guid)
97 }
98
99 /// Indicates if the GUID is mentioned in the tree, either as a node or
100 /// a deletion.
101 #[inline]
102 pub fn mentions(&self, guid: &Guid) -> bool {
103 self.entry_index_by_guid.contains_key(guid) || self.deleted_guids.contains(guid)
104 }
105
106 /// Returns an iterator for all node and tombstone GUIDs.
107 pub fn guids(&self) -> impl Iterator<Item = &Guid> {
108 self.entries
109 .iter()
110 .map(|entry| &entry.item.guid)
111 .chain(self.deleted_guids.iter())
112 }
113
114 /// Returns the node for a given `guid`, or `None` if a node with the `guid`
115 /// doesn't exist in the tree, or was deleted.
116 pub fn node_for_guid(&self, guid: &Guid) -> Option<Node<'_>> {
117 self.entry_index_by_guid
118 .get(guid)
119 .map(|&index| Node(self, &self.entries[index]))
120 }
121
122 /// Returns the structure divergences found when building the tree.
123 #[inline]
124 pub fn problems(&self) -> &Problems {
125 &self.problems
126 }
127 }
128
129 impl fmt::Display for Tree {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 let root = self.root();
132 f.write_str(&root.to_ascii_string())?;
133 if !self.deleted_guids.is_empty() {
134 f.write_str("\nDeleted: [")?;
135 for (i, guid) in self.deleted_guids.iter().enumerate() {
136 if i != 0 {
137 f.write_str(", ")?;
138 }
139 f.write_str(guid.as_ref())?;
140 }
141 }
142 if !self.problems.is_empty() {
143 f.write_str("\nProblems:\n")?;
144 for (i, summary) in self.problems.summarize().enumerate() {
145 if i != 0 {
146 f.write_str("\n")?;
147 }
148 write!(f, "❗️ {}", summary)?;
149 }
150 }
151 Ok(())
152 }
153 }
154
155 /// A tree builder builds a bookmark tree structure from a flat list of items
156 /// and parent-child associations.
157 ///
158 /// # Tree structure
159 ///
160 /// In a well-formed tree:
161 ///
162 /// - Each item exists in exactly one folder. Two different folder's
163 /// `children` should never reference the same item.
164 /// - Each folder contains existing children. A folder's `children` should
165 /// never reference tombstones, or items that don't exist in the tree at all.
166 /// - Each item has a `parentid` that agrees with its parent's `children`. In
167 /// other words, if item B's `parentid` is A, then A's `children` should
168 /// contain B.
169 ///
170 /// Because of Reasons, things are (a lot) messier in practice.
171 ///
172 /// # Structure inconsistencies
173 ///
174 /// Sync stores structure in two places: a `parentid` property on each item,
175 /// which points to its parent's GUID, and a list of ordered `children` on the
176 /// item's parent. They're duplicated because, historically, Sync clients didn't
177 /// stage incoming records. Instead, they applied records one at a time,
178 /// directly to the live local tree. This meant that, if a client saw a child
179 /// before its parent, it would first use the `parentid` to decide where to keep
180 /// the child, then fix up parents and positions using the parent's `children`.
181 ///
182 /// This is also why moving an item into a different folder uploads records for
183 /// the item, old folder, and new folder. The item has a new `parentid`, and the
184 /// folders have new `children`. Similarly, deleting an item uploads a tombstone
185 /// for the item, and a record for the item's old parent.
186 ///
187 /// Unfortunately, bugs (bug 1258127) and missing features (bug 1253051) in
188 /// older clients sometimes caused them to upload invalid or incomplete changes.
189 /// For example, a client might have:
190 ///
191 /// - Uploaded a moved child, but not its parents. This means the child now
192 /// appears in multiple parents. In the most extreme case, an item might be
193 /// referenced in two different sets of `children`, _and_ have a third,
194 /// completely unrelated `parentid`.
195 /// - Deleted a child, and tracked the deletion, but didn't flag the parent for
196 /// reupload. The parent folder now has a tombstone child.
197 /// - Tracked and uploaded items that shouldn't exist on the server at all,
198 /// like the left pane or reading list roots (bug 1309255).
199 /// - Missed new folders created during a sync, creating holes in the tree.
200 ///
201 /// Newer clients shouldn't do this, but we might still have inconsistent
202 /// records on the server that will confuse older clients. Additionally, Firefox
203 /// for iOS includes a much stricter bookmarks engine that refuses to sync if
204 /// it detects inconsistencies.
205 ///
206 /// # Divergences
207 ///
208 /// To work around this, the builder lets the structure _diverge_. This allows:
209 ///
210 /// - Items with multiple parents.
211 /// - Items with missing `parentid`s.
212 /// - Folders with `children` whose `parentid`s don't match the folder.
213 /// - Items whose `parentid`s don't mention the item in their `children`.
214 /// - Items with `parentid`s that point to nonexistent or deleted folders.
215 /// - Folders with nonexistent `children`.
216 /// - Non-syncable items, like custom roots.
217 /// - Any combination of these.
218 ///
219 /// # Resolving divergences
220 ///
221 /// Building a tree using `std::convert::TryInto<Tree>::try_into` resolves
222 /// divergences using these rules:
223 ///
224 /// 1. User content roots should always be children of the Places root. If
225 /// they appear in other parents, we move them.
226 /// 2. Items that appear in multiple `children`, and items with mismatched
227 /// `parentid`s, use the chronologically newer parent, based on the parent's
228 /// last modified time. We always prefer parents by `children` over
229 /// `parentid,` because `children` also gives us the item's position.
230 /// 3. Items that aren't mentioned in any parent's `children`, but have a
231 /// `parentid` that references an existing folder in the tree, are reparented
232 /// to the end of that folder, after the folder's `children`.
233 /// 4. Items that reference a nonexistent or non-folder `parentid`, or don't
234 /// have a `parentid` at all, are reparented to the default folder.
235 /// 5. If the default folder isn't set, or doesn't exist, items from rule 4 are
236 /// reparented to the root instead.
237 ///
238 /// The result is a well-formed tree structure that can be merged. The merger
239 /// detects if the structure diverged, and flags affected items for reupload.
240 #[derive(Debug)]
241 pub struct Builder {
242 entry_index_by_guid: HashMap<Guid, Index>,
243 entries: Vec<BuilderEntry>,
244 deleted_guids: HashSet<Guid>,
245 reparent_orphans_to: Option<Guid>,
246 }
247
248 impl Builder {
249 /// Sets the default folder for reparented orphans. If not set, doesn't
250 /// exist, or not a folder, orphans will be reparented to the root.
251 #[inline]
252 pub fn reparent_orphans_to(&mut self, guid: &Guid) -> &mut Builder {
253 self.reparent_orphans_to = Some(guid.clone());
254 self
255 }
256
257 /// Inserts an `item` into the tree. Returns an error if the item already
258 /// exists.
259 pub fn item(&mut self, item: Item) -> Result<ItemBuilder<'_>> {
260 assert_eq!(self.entries.len(), self.entry_index_by_guid.len());
261 if self.entry_index_by_guid.contains_key(&item.guid) {
262 return Err(ErrorKind::DuplicateItem(item.guid.clone()).into());
263 }
264 let entry_index = self.entries.len();
265 self.entry_index_by_guid
266 .insert(item.guid.clone(), entry_index);
267 self.entries.push(BuilderEntry {
268 item,
269 content: None,
270 parent: BuilderEntryParent::None,
271 children: Vec::new(),
272 });
273 Ok(ItemBuilder(self, entry_index))
274 }
275
276 /// Sets parents for a `child_guid`. Depending on where the parent comes
277 /// from, `child_guid` may not need to exist in the tree.
278 pub fn parent_for(&mut self, child_guid: &Guid) -> ParentBuilder<'_> {
279 assert_eq!(self.entries.len(), self.entry_index_by_guid.len());
280 let entry_child = match self.entry_index_by_guid.get(child_guid) {
281 Some(&child_index) => BuilderEntryChild::Exists(child_index),
282 None => BuilderEntryChild::Missing(child_guid.clone()),
283 };
284 ParentBuilder(self, entry_child)
285 }
286
287 /// Notes a tombstone for a deleted item, marking it as deleted in the
288 /// tree.
289 #[inline]
290 pub fn deletion(&mut self, guid: Guid) -> &mut Builder {
291 self.deleted_guids.insert(guid);
292 self
293 }
294
295 /// Equivalent to using our implementation of`TryInto<Tree>::try_into`, but
296 /// provided both for convenience when updating from previous versions of
297 /// `dogear`, and for cases where a type hint would otherwise be needed to
298 /// clarify the target type of the conversion.
299 pub fn into_tree(self) -> Result<Tree> {
300 self.try_into()
301 }
302
303 /// Mutates content and structure for an existing item. This is only
304 /// exposed to tests.
305 #[cfg(test)]
306 pub fn mutate(&mut self, child_guid: &Guid) -> ItemBuilder<'_> {
307 assert_eq!(self.entries.len(), self.entry_index_by_guid.len());
308 match self.entry_index_by_guid.get(child_guid) {
309 Some(&child_index) => ItemBuilder(self, child_index),
310 None => panic!("Can't mutate nonexistent item {}", child_guid),
311 }
312 }
313 }
314
315 impl TryFrom<Builder> for Tree {
316 type Error = Error;
317 /// Builds a tree from all stored items and parent-child associations,
318 /// resolving inconsistencies like orphans, multiple parents, and
319 /// parent-child disagreements.
320 fn try_from(mut builder: Builder) -> Result<Tree> {
321 let mut problems = Problems::default();
322
323 // The indices in this bit vector point to zombie entries, which exist
324 // in the tree, but are also flagged as deleted. We'll remove these
325 // zombies from the set of deleted GUIDs, and mark them as diverged for
326 // reupload.
327 let mut zombies = SmallBitVec::from_elem(builder.entries.len(), false);
328
329 // First, resolve parents for all entries, and build a lookup table for
330 // items without a position.
331 let mut parents = Vec::with_capacity(builder.entries.len());
332 let mut reparented_child_indices_by_parent: HashMap<Index, Vec<Index>> = HashMap::new();
333 for (entry_index, entry) in builder.entries.iter().enumerate() {
334 if entry.item.validity == Validity::Replace {
335 problems.note(&entry.item.guid, Problem::InvalidItem);
336 }
337 let r = ResolveParent::new(&builder, entry, &mut problems);
338 let resolved_parent = r.resolve();
339 if let ResolvedParent::ByParentGuid(parent_index) = resolved_parent {
340 // Reparented items are special: since they aren't mentioned in
341 // that parent's `children`, we don't know their positions. Note
342 // them for when we resolve children. We also clone the GUID,
343 // since we use it for sorting, but can't access it by
344 // reference once we call `builder.entries.into_iter()` below.
345 let reparented_child_indices = reparented_child_indices_by_parent
346 .entry(parent_index)
347 .or_default();
348 reparented_child_indices.push(entry_index);
349 }
350 if builder.deleted_guids.remove(&entry.item.guid) {
351 zombies.set(entry_index, true);
352 }
353 parents.push(resolved_parent);
354 }
355
356 // If any parents form cycles, abort. We haven't seen cyclic trees in
357 // the wild, and breaking cycles would add complexity.
358 if let Some(index) = detect_cycles(&parents) {
359 return Err(ErrorKind::Cycle(builder.entries[index].item.guid.clone()).into());
360 }
361
362 // Then, resolve children, and build a slab of entries for the tree.
363 let mut entries = Vec::with_capacity(builder.entries.len());
364 for (entry_index, entry) in builder.entries.into_iter().enumerate() {
365 // Each entry is consistent, until proven otherwise!
366 let mut divergence = Divergence::Consistent;
367
368 let parent_index = match &parents[entry_index] {
369 ResolvedParent::Root => {
370 // The Places root doesn't have a parent, and should always
371 // be the first entry.
372 assert_eq!(entry_index, 0);
373 None
374 }
375 ResolvedParent::ByStructure(index) => {
376 // The entry has a valid parent by structure, yay!
377 Some(*index)
378 }
379 ResolvedParent::ByChildren(index) | ResolvedParent::ByParentGuid(index) => {
380 // The entry has multiple parents, and we resolved one,
381 // so it's diverged.
382 divergence = Divergence::Diverged;
383 Some(*index)
384 }
385 };
386
387 // If the entry is a zombie, mark it as diverged, so that the merger
388 // can remove the tombstone and reupload the item.
389 if zombies[entry_index] {
390 divergence = Divergence::Diverged;
391 }
392
393 // Check if the entry's children exist and agree that this entry is
394 // their parent.
395 let mut child_indices = Vec::with_capacity(entry.children.len());
396 for child in entry.children {
397 match child {
398 BuilderEntryChild::Exists(child_index) => {
399 if zombies[entry_index] {
400 // If the entry has a zombie child, mark it as
401 // diverged.
402 divergence = Divergence::Diverged;
403 }
404 match &parents[child_index] {
405 ResolvedParent::Root => {
406 // The Places root can't be a child of another entry.
407 unreachable!("A child can't be a top-level root");
408 }
409 ResolvedParent::ByStructure(parent_index) => {
410 // If the child has a valid parent by structure, it
411 // must be the entry. If it's not, there's a bug
412 // in `ResolveParent` or `BuilderEntry`.
413 assert_eq!(*parent_index, entry_index);
414 child_indices.push(child_index);
415 }
416 ResolvedParent::ByChildren(parent_index) => {
417 // If the child has multiple parents, we may have
418 // resolved a different one, so check if we decided
419 // to keep the child in this entry.
420 divergence = Divergence::Diverged;
421 if *parent_index == entry_index {
422 child_indices.push(child_index);
423 }
424 }
425 ResolvedParent::ByParentGuid(parent_index) => {
426 // We should only ever prefer parents
427 // `by_parent_guid` over parents `by_children` for
428 // misparented user content roots. Otherwise,
429 // there's a bug in `ResolveParent`.
430 assert_eq!(*parent_index, 0);
431 divergence = Divergence::Diverged;
432 }
433 }
434 }
435 BuilderEntryChild::Missing(child_guid) => {
436 // If the entry's `children` mention a deleted or
437 // nonexistent GUID, note it as a problem, and ignore
438 // the child.
439 divergence = Divergence::Diverged;
440 let problem = if builder.deleted_guids.remove(&child_guid) {
441 Problem::DeletedChild {
442 child_guid: child_guid.clone(),
443 }
444 } else {
445 Problem::MissingChild {
446 child_guid: child_guid.clone(),
447 }
448 };
449 problems.note(&entry.item.guid, problem);
450 }
451 }
452 }
453
454 // Reparented items don't appear in our `children`, so we move them
455 // to the end, after existing children (rules 3-4).
456 if let Some(reparented_child_indices) =
457 reparented_child_indices_by_parent.get(&entry_index)
458 {
459 divergence = Divergence::Diverged;
460 child_indices.extend_from_slice(reparented_child_indices);
461 }
462
463 entries.push(TreeEntry {
464 item: entry.item,
465 content: entry.content,
466 parent_index,
467 child_indices,
468 divergence,
469 });
470 }
471
472 // Now we have a consistent tree.
473 Ok(Tree {
474 entry_index_by_guid: builder.entry_index_by_guid,
475 entries,
476 deleted_guids: builder.deleted_guids,
477 problems,
478 })
479 }
480 }
481
482 /// Adds an item with content and structure to a tree builder.
483 pub struct ItemBuilder<'b>(&'b mut Builder, Index);
484
485 impl<'b> ItemBuilder<'b> {
486 /// Sets content info for an item that hasn't been uploaded or merged yet.
487 /// We'll try to dedupe local items with content info to remotely changed
488 /// items with similar contents and different GUIDs.
489 #[inline]
490 pub fn content<'c>(&'c mut self, content: Content) -> &'c mut ItemBuilder<'b> {
491 self.0.entries[self.1].content = Some(content);
492 self
493 }
494
495 /// Records a `parent_guid` from the item's parent's `children`. See
496 /// `ParentBuilder::by_children`.
497 #[inline]
498 pub fn by_children(self, parent_guid: &Guid) -> Result<&'b mut Builder> {
499 let b = ParentBuilder(self.0, BuilderEntryChild::Exists(self.1));
500 b.by_children(parent_guid)
501 }
502
503 /// Records a `parent_guid` from the item's `parentid`. See
504 /// `ParentBuilder::by_parent_guid`.
505 #[inline]
506 pub fn by_parent_guid(self, parent_guid: Guid) -> Result<&'b mut Builder> {
507 let b = ParentBuilder(self.0, BuilderEntryChild::Exists(self.1));
508 b.by_parent_guid(parent_guid)
509 }
510
511 #[inline]
512 pub fn by_structure(self, parent_guid: &Guid) -> Result<&'b mut Builder> {
513 let b = ParentBuilder(self.0, BuilderEntryChild::Exists(self.1));
514 b.by_structure(parent_guid)
515 }
516 }
517
518 /// Adds structure for an existing item to a tree builder.
519 pub struct ParentBuilder<'b>(&'b mut Builder, BuilderEntryChild);
520
521 impl<'b> ParentBuilder<'b> {
522 /// Records a `parent_guid` from the item's parent's `children`. The
523 /// `parent_guid` must refer to an existing folder in the tree, but
524 /// the item itself doesn't need to exist. This handles folders with
525 /// missing children.
526 pub fn by_children(self, parent_guid: &Guid) -> Result<&'b mut Builder> {
527 let parent_index = match self.0.entry_index_by_guid.get(parent_guid) {
528 Some(&parent_index) if self.0.entries[parent_index].item.is_folder() => parent_index,
529 Some(&parent_index) => {
530 let parent = &self.0.entries[parent_index].item;
531
532 let child = match &self.1 {
533 BuilderEntryChild::Exists(index) => &self.0.entries[*index].item,
534 BuilderEntryChild::Missing(child_guid) => {
535 return Err(ErrorKind::InvalidParentForUnknownChild(
536 child_guid.clone(),
537 parent.clone(),
538 )
539 .into())
540 }
541 };
542
543 return Err(ErrorKind::InvalidParent(child.clone(), parent.clone()).into());
544 }
545 _ => {
546 let child = match &self.1 {
547 BuilderEntryChild::Exists(index) => &self.0.entries[*index].item,
548 BuilderEntryChild::Missing(child_guid) => {
549 return Err(ErrorKind::MissingParentForUnknownChild(
550 child_guid.clone(),
551 parent_guid.clone(),
552 )
553 .into())
554 }
555 };
556
557 return Err(ErrorKind::MissingParent(child.clone(), parent_guid.clone()).into());
558 }
559 };
560 if let BuilderEntryChild::Exists(child_index) = &self.1 {
561 self.0.entries[*child_index].parents_by(&[BuilderParentBy::Children(parent_index)])?;
562 }
563 self.0.entries[parent_index].children.push(self.1);
564 Ok(self.0)
565 }
566
567 /// Records a `parent_guid` from the item's `parentid`. The item must
568 /// exist in the tree, but the `parent_guid` doesn't need to exist,
569 /// or even refer to a folder. The builder will reparent items with
570 /// missing and non-folder `parentid`s to the default folder when it
571 /// builds the tree.
572 pub fn by_parent_guid(self, parent_guid: Guid) -> Result<&'b mut Builder> {
573 match &self.1 {
574 BuilderEntryChild::Exists(child_index) => {
575 self.0.entries[*child_index]
576 .parents_by(&[BuilderParentBy::UnknownItem(parent_guid)])?;
577 }
578 BuilderEntryChild::Missing(child_guid) => {
579 return Err(ErrorKind::MissingItem(child_guid.clone()).into());
580 }
581 }
582 Ok(self.0)
583 }
584
585 /// Records a `parent_guid` from a valid tree structure. This is for
586 /// callers who already know their structure is consistent, like
587 /// `Store::fetch_local_tree()` on Desktop, and
588 /// `std::convert::TryInto<Tree>` in the tests.
589 ///
590 /// Both the item and `parent_guid` must exist, and the `parent_guid` must
591 /// refer to a folder.
592 ///
593 /// `by_structure(parent_guid)` is logically the same as:
594 ///
595 /// ```no_run
596 /// # use dogear::{Item, Kind, Result, ROOT_GUID, Tree};
597 /// # fn main() -> Result<()> {
598 /// # let mut builder = Tree::with_root(Item::new(ROOT_GUID, Kind::Folder));
599 /// # let child_guid = "bookmarkAAAA".into();
600 /// # let parent_guid = "folderAAAAAA".into();
601 /// builder.parent_for(&child_guid)
602 /// .by_children(&parent_guid)?
603 /// .parent_for(&child_guid)
604 /// .by_parent_guid(parent_guid)?;
605 /// # Ok(())
606 /// # }
607 /// ```
608 ///
609 /// ...But more convenient. It's also more efficient, because it avoids
610 /// multiple lookups for the item and parent, as well as an extra heap
611 /// allocation to store the parents.
612 pub fn by_structure(self, parent_guid: &Guid) -> Result<&'b mut Builder> {
613 let parent_index = match self.0.entry_index_by_guid.get(parent_guid) {
614 Some(&parent_index) if self.0.entries[parent_index].item.is_folder() => parent_index,
615 Some(&parent_index) => {
616 let parent = &self.0.entries[parent_index].item;
617
618 let child = match &self.1 {
619 BuilderEntryChild::Exists(index) => &self.0.entries[*index].item,
620 BuilderEntryChild::Missing(child_guid) => {
621 return Err(ErrorKind::InvalidParentForUnknownChild(
622 child_guid.clone(),
623 parent.clone(),
624 )
625 .into())
626 }
627 };
628
629 return Err(ErrorKind::InvalidParent(child.clone(), parent.clone()).into());
630 }
631 _ => {
632 let child = match &self.1 {
633 BuilderEntryChild::Exists(index) => &self.0.entries[*index].item,
634 BuilderEntryChild::Missing(child_guid) => {
635 return Err(ErrorKind::MissingParentForUnknownChild(
636 child_guid.clone(),
637 parent_guid.clone(),
638 )
639 .into())
640 }
641 };
642
643 return Err(ErrorKind::MissingParent(child.clone(), parent_guid.clone()).into());
644 }
645 };
646 if let BuilderEntryChild::Exists(child_index) = &self.1 {
647 self.0.entries[*child_index].parents_by(&[
648 BuilderParentBy::Children(parent_index),
649 BuilderParentBy::KnownItem(parent_index),
650 ])?;
651 }
652 self.0.entries[parent_index].children.push(self.1);
653 Ok(self.0)
654 }
655 }
656
657 /// An entry wraps a tree item with references to its parents and children,
658 /// which index into the tree's `entries` vector. This indirection exists
659 /// because Rust is more strict about ownership of parents and children.
660 ///
661 /// For example, we can't have entries own their children without sacrificing
662 /// fast random lookup: we'd need to store references to the entries in the
663 /// lookup map, but a struct can't hold references into itself.
664 ///
665 /// Similarly, we can't have entries hold `Weak` pointers to `Rc` entries for
666 /// the parent and children, because we need to update the parent when we insert
667 /// a new node, but `Rc` won't hand us a mutable reference to the entry as long
668 /// as it has outstanding `Weak` pointers.
669 ///
670 /// We *could* use GUIDs instead of indices, and store the entries in a
671 /// `HashMap<String, Entry>`, but that's inefficient: we'd need to store N
672 /// copies of the GUID for parent and child lookups, and retrieving children
673 /// would take one hash map lookup *per child*.
674 ///
675 /// Note that we always compare references to entries, instead of deriving
676 /// `PartialEq`, because two entries with the same fields but in different
677 /// trees should never compare equal.
678 #[derive(Debug)]
679 struct TreeEntry {
680 item: Item,
681 content: Option<Content>,
682 divergence: Divergence,
683 parent_index: Option<Index>,
684 child_indices: Vec<Index>,
685 }
686
687 /// A builder entry holds an item and its structure. It's the builder's analog
688 /// of a `TreeEntry`.
689 #[derive(Debug)]
690 struct BuilderEntry {
691 item: Item,
692 content: Option<Content>,
693 parent: BuilderEntryParent,
694 children: Vec<BuilderEntryChild>,
695 }
696
697 impl BuilderEntry {
698 /// Adds `new_parents` for the entry.
699 fn parents_by(&mut self, new_parents: &[BuilderParentBy]) -> Result<()> {
700 let old_parent = mem::replace(&mut self.parent, BuilderEntryParent::None);
701 let new_parent = match old_parent {
702 BuilderEntryParent::Root => {
703 self.parent = BuilderEntryParent::Root;
704 return Err(ErrorKind::DuplicateItem(self.item.guid.clone()).into());
705 }
706 BuilderEntryParent::None => match new_parents {
707 [BuilderParentBy::Children(from_children), BuilderParentBy::KnownItem(from_item)]
708 | [BuilderParentBy::KnownItem(from_item), BuilderParentBy::Children(from_children)]
709 if from_children == from_item =>
710 {
711 // If the parent's `children` and item's `parentid` match,
712 // we have a complete structure, so we can avoid an extra
713 // allocation for the partial structure.
714 BuilderEntryParent::Complete(*from_children)
715 }
716 new_parents => BuilderEntryParent::Partial(new_parents.to_vec()),
717 },
718 BuilderEntryParent::Complete(index) => {
719 let mut parents = vec![
720 BuilderParentBy::Children(index),
721 BuilderParentBy::KnownItem(index),
722 ];
723 parents.extend_from_slice(new_parents);
724 BuilderEntryParent::Partial(parents)
725 }
726 BuilderEntryParent::Partial(mut parents) => {
727 parents.extend_from_slice(new_parents);
728 BuilderEntryParent::Partial(parents)
729 }
730 };
731 self.parent = new_parent;
732 Ok(())
733 }
734 }
735
736 /// Holds an existing child index, or missing child GUID, for a builder entry.
737 #[derive(Debug)]
738 enum BuilderEntryChild {
739 Exists(Index),
740 Missing(Guid),
741 }
742
743 /// Holds one or more parents for a builder entry.
744 #[derive(Clone, Debug)]
745 enum BuilderEntryParent {
746 /// The entry is an orphan.
747 None,
748
749 /// The entry is a top-level root, from which all other entries descend.
750 /// A tree can only have one root.
751 Root,
752
753 /// The entry has two matching parents from its structure. This is the fast
754 /// path for local trees, which are always valid.
755 Complete(Index),
756
757 /// The entry has an incomplete or divergent structure. This is the path for
758 /// all remote trees, valid and invalid, since we add structure from
759 /// `parentid`s and `children` separately. This is also the path for
760 /// mismatched and multiple parents.
761 Partial(Vec<BuilderParentBy>),
762 }
763
764 /// Describes where a builder entry's parent comes from.
765 #[derive(Clone, Debug)]
766 enum BuilderParentBy {
767 /// The entry's parent references the entry in its `children`.
768 Children(Index),
769
770 /// The entry's parent comes from its `parentid`, and will be resolved
771 /// when we build the tree.
772 UnknownItem(Guid),
773
774 /// The entry's parent comes from its `parentid` and has been
775 /// resolved.
776 KnownItem(Index),
777 }
778
779 /// Resolves the parent for a builder entry.
780 struct ResolveParent<'a> {
781 builder: &'a Builder,
782 entry: &'a BuilderEntry,
783 problems: &'a mut Problems,
784 }
785
786 impl<'a> ResolveParent<'a> {
787 fn new(
788 builder: &'a Builder,
789 entry: &'a BuilderEntry,
790 problems: &'a mut Problems,
791 ) -> ResolveParent<'a> {
792 ResolveParent {
793 builder,
794 entry,
795 problems,
796 }
797 }
798
799 fn resolve(self) -> ResolvedParent {
800 if self.entry.item.guid.is_built_in_root() {
801 self.user_content_root()
802 } else {
803 self.item()
804 }
805 }
806
807 /// Returns the parent for this builder entry. This unifies parents
808 /// `by_structure`, which are known to be consistent, and parents
809 /// `by_children` and `by_parent_guid`, which are consistent if they match.
810 fn parent(&self) -> Cow<'a, BuilderEntryParent> {
811 let parents = match &self.entry.parent {
812 // Roots and orphans pass through as-is.
813 BuilderEntryParent::Root => return Cow::Owned(BuilderEntryParent::Root),
814 BuilderEntryParent::None => return Cow::Owned(BuilderEntryParent::None),
815 BuilderEntryParent::Complete(index) => {
816 // The entry is known to have a valid parent by structure. This
817 // is the fast path, used for local trees in Desktop.
818 return Cow::Owned(BuilderEntryParent::Complete(*index));
819 }
820 BuilderEntryParent::Partial(parents) => parents,
821 };
822 // The entry has zero, one, or many parents, recorded separately. Check
823 // if it has exactly two: one `by_parent_guid`, and one `by_children`.
824 let (index_by_guid, index_by_children) = match parents.as_slice() {
825 [BuilderParentBy::UnknownItem(guid), BuilderParentBy::Children(index_by_children)]
826 | [BuilderParentBy::Children(index_by_children), BuilderParentBy::UnknownItem(guid)] => {
827 match self.builder.entry_index_by_guid.get(guid) {
828 Some(&index_by_guid) => (index_by_guid, *index_by_children),
829 None => return Cow::Borrowed(&self.entry.parent),
830 }
831 }
832 [BuilderParentBy::KnownItem(index_by_guid), BuilderParentBy::Children(index_by_children)]
833 | [BuilderParentBy::Children(index_by_children), BuilderParentBy::KnownItem(index_by_guid)] => {
834 (*index_by_guid, *index_by_children)
835 }
836 // In all other cases (missing `parentid`, missing from `children`,
837 // multiple parents), return all possible parents. We'll pick one
838 // when we resolve the parent.
839 _ => return Cow::Borrowed(&self.entry.parent),
840 };
841 // If the entry has matching parents `by_children` and `by_parent_guid`,
842 // it has a valid parent by structure. This is the "fast slow path",
843 // used for remote trees in Desktop, because their structure is built in
844 // two passes. In all other cases, we have a parent-child disagreement,
845 // so return all possible parents.
846 if index_by_guid == index_by_children {
847 Cow::Owned(BuilderEntryParent::Complete(index_by_children))
848 } else {
849 Cow::Borrowed(&self.entry.parent)
850 }
851 }
852
853 /// Resolves the parent for a user content root: menu, mobile, toolbar, and
854 /// unfiled. These are simpler to resolve than non-roots because they must
855 /// be children of the Places root (rule 1), which is always the first
856 /// entry.
857 fn user_content_root(self) -> ResolvedParent {
858 match self.parent().as_ref() {
859 BuilderEntryParent::None => {
860 // Orphaned content root. This should only happen if the content
861 // root doesn't have a parent `by_parent_guid`.
862 self.problems.note(&self.entry.item.guid, Problem::Orphan);
863 ResolvedParent::ByParentGuid(0)
864 }
865 BuilderEntryParent::Root => {
866 unreachable!("A user content root can't be a top-level root")
867 }
868 BuilderEntryParent::Complete(index) => {
869 if *index == 0 {
870 ResolvedParent::ByStructure(*index)
871 } else {
872 // Move misparented content roots to the Places root.
873 let parent_guid = self.builder.entries[*index].item.guid.clone();
874 self.problems.note(
875 &self.entry.item.guid,
876 Problem::MisparentedRoot(vec![
877 DivergedParent::ByChildren(parent_guid.clone()),
878 DivergedParentGuid::Folder(parent_guid).into(),
879 ]),
880 );
881 ResolvedParent::ByParentGuid(0)
882 }
883 }
884 BuilderEntryParent::Partial(parents_by) => {
885 // Ditto for content roots with multiple parents or parent-child
886 // disagreements.
887 self.problems.note(
888 &self.entry.item.guid,
889 Problem::MisparentedRoot(
890 parents_by
891 .iter()
892 .map(|parent_by| {
893 PossibleParent::new(self.builder, parent_by).summarize()
894 })
895 .collect(),
896 ),
897 );
898 ResolvedParent::ByParentGuid(0)
899 }
900 }
901 }
902
903 /// Resolves the parent for a top-level Places root or other item, using
904 /// rules 2-5.
905 fn item(self) -> ResolvedParent {
906 match self.parent().as_ref() {
907 BuilderEntryParent::Root => ResolvedParent::Root,
908 BuilderEntryParent::None => {
909 // The item doesn't have a `parentid`, and isn't mentioned in
910 // any `children`. Reparent to the default folder (rule 4) or
911 // Places root (rule 5).
912 let parent_index = self.reparent_orphans_to_default_index();
913 self.problems.note(&self.entry.item.guid, Problem::Orphan);
914 ResolvedParent::ByParentGuid(parent_index)
915 }
916 BuilderEntryParent::Complete(index) => {
917 // The item's `parentid` and parent's `children` match, so keep
918 // it in its current parent.
919 ResolvedParent::ByStructure(*index)
920 }
921 BuilderEntryParent::Partial(parents) => {
922 // For items with one or more than two parents, pick the
923 // youngest (minimum age).
924 let possible_parents = parents
925 .iter()
926 .map(|parent_by| PossibleParent::new(self.builder, parent_by))
927 .collect::<Vec<_>>();
928 self.problems.note(
929 &self.entry.item.guid,
930 Problem::DivergedParents(
931 possible_parents
932 .iter()
933 .map(PossibleParent::summarize)
934 .collect(),
935 ),
936 );
937 possible_parents
938 .into_iter()
939 .min()
940 .and_then(|p| match p.parent_by {
941 BuilderParentBy::Children(index) => {
942 Some(ResolvedParent::ByChildren(*index))
943 }
944 BuilderParentBy::KnownItem(index) => {
945 Some(ResolvedParent::ByParentGuid(*index))
946 }
947 BuilderParentBy::UnknownItem(guid) => self
948 .builder
949 .entry_index_by_guid
950 .get(guid)
951 .filter(|&&index| self.builder.entries[index].item.is_folder())
952 .map(|&index| ResolvedParent::ByParentGuid(index)),
953 })
954 .unwrap_or_else(|| {
955 // Fall back to the default folder (rule 4) or root
956 // (rule 5) if we didn't find a parent.
957 let parent_index = self.reparent_orphans_to_default_index();
958 ResolvedParent::ByParentGuid(parent_index)
959 })
960 }
961 }
962 }
963
964 /// Returns the index of the default parent entry for reparented orphans.
965 /// This is either the default folder (rule 4), or the root, if the
966 /// default folder isn't set, doesn't exist, or isn't a folder (rule 5).
967 fn reparent_orphans_to_default_index(&self) -> Index {
968 self.builder
969 .reparent_orphans_to
970 .as_ref()
971 .and_then(|guid| self.builder.entry_index_by_guid.get(guid))
972 .cloned()
973 .filter(|&parent_index| {
974 let parent_entry = &self.builder.entries[parent_index];
975 parent_entry.item.is_folder()
976 })
977 .unwrap_or(0)
978 }
979 }
980
981 // A possible parent for an item with conflicting parents. We use this wrapper's
982 // `Ord` implementation to decide which parent is youngest.
983 #[derive(Clone, Copy, Debug)]
984 struct PossibleParent<'a> {
985 builder: &'a Builder,
986 parent_by: &'a BuilderParentBy,
987 }
988
989 impl<'a> PossibleParent<'a> {
990 fn new(builder: &'a Builder, parent_by: &'a BuilderParentBy) -> PossibleParent<'a> {
991 PossibleParent { builder, parent_by }
992 }
993
994 /// Returns the problem with this conflicting parent.
995 fn summarize(&self) -> DivergedParent {
996 let entry = match self.parent_by {
997 BuilderParentBy::Children(index) => {
998 return DivergedParent::ByChildren(self.builder.entries[*index].item.guid.clone());
999 }
1000 BuilderParentBy::KnownItem(index) => &self.builder.entries[*index],
1001 BuilderParentBy::UnknownItem(guid) => {
1002 match self.builder.entry_index_by_guid.get(guid) {
1003 Some(index) => &self.builder.entries[*index],
1004 None => {
1005 if self.builder.deleted_guids.contains(guid) {
1006 return DivergedParentGuid::Deleted(guid.clone()).into();
1007 }
1008 return DivergedParentGuid::Missing(guid.clone()).into();
1009 }
1010 }
1011 }
1012 };
1013 if entry.item.is_folder() {
1014 DivergedParentGuid::Folder(entry.item.guid.clone()).into()
1015 } else {
1016 DivergedParentGuid::NonFolder(entry.item.guid.clone()).into()
1017 }
1018 }
1019 }
1020
1021 impl<'a> Ord for PossibleParent<'a> {
1022 /// Compares two possible parents to determine which is younger
1023 /// (`Ordering::Less`). Prefers parents from `children` over `parentid`
1024 /// (rule 2), and `parentid`s that reference folders over non-folders
1025 /// (rule 4).
1026 fn cmp(&self, other: &PossibleParent<'_>) -> Ordering {
1027 let (index, other_index) = match (&self.parent_by, &other.parent_by) {
1028 (BuilderParentBy::Children(index), BuilderParentBy::Children(other_index)) => {
1029 // Both `self` and `other` mention the item in their `children`.
1030 (*index, *other_index)
1031 }
1032 (BuilderParentBy::Children(_), BuilderParentBy::KnownItem(_)) => {
1033 // `self` mentions the item in its `children`, and the item's
1034 // `parentid` is `other`, so prefer `self`.
1035 return Ordering::Less;
1036 }
1037 (BuilderParentBy::Children(_), BuilderParentBy::UnknownItem(_)) => {
1038 // As above, except we don't know if `other` exists. We don't
1039 // need to look it up, though, because we can unconditionally
1040 // prefer `self`.
1041 return Ordering::Less;
1042 }
1043 (BuilderParentBy::KnownItem(_), BuilderParentBy::Children(_)) => {
1044 // The item's `parentid` is `self`, and `other` mentions the
1045 // item in its `children`, so prefer `other`.
1046 return Ordering::Greater;
1047 }
1048 (BuilderParentBy::UnknownItem(_), BuilderParentBy::Children(_)) => {
1049 // As above. We don't know if `self` exists, but we
1050 // unconditionally prefer `other`.
1051 return Ordering::Greater;
1052 }
1053 // Cases where `self` and `other` are `parentid`s, existing or not,
1054 // are academic, since it doesn't make sense for an item to have
1055 // multiple `parentid`s.
1056 _ => return Ordering::Equal,
1057 };
1058 // If both `self` and `other` are folders, compare timestamps. If one is
1059 // a folder, but the other isn't, we prefer the folder. If neither is a
1060 // folder, it doesn't matter.
1061 let entry = &self.builder.entries[index];
1062 let other_entry = &self.builder.entries[other_index];
1063 match (entry.item.is_folder(), other_entry.item.is_folder()) {
1064 (true, true) => entry.item.age.cmp(&other_entry.item.age),
1065 (false, true) => Ordering::Greater,
1066 (true, false) => Ordering::Less,
1067 (false, false) => Ordering::Equal,
1068 }
1069 }
1070 }
1071
1072 impl<'a> PartialOrd for PossibleParent<'a> {
1073 fn partial_cmp(&self, other: &PossibleParent<'_>) -> Option<Ordering> {
1074 Some(self.cmp(other))
1075 }
1076 }
1077
1078 impl<'a> PartialEq for PossibleParent<'a> {
1079 fn eq(&self, other: &PossibleParent<'_>) -> bool {
1080 self.cmp(other) == Ordering::Equal
1081 }
1082 }
1083
1084 impl<'a> Eq for PossibleParent<'a> {}
1085
1086 /// Describes a resolved parent for an item.
1087 #[derive(Debug)]
1088 enum ResolvedParent {
1089 /// The item is a top-level root, and has no parent.
1090 Root,
1091
1092 /// The item has a valid, consistent structure.
1093 ByStructure(Index),
1094
1095 /// The item has multiple parents; this is the one we picked.
1096 ByChildren(Index),
1097
1098 /// The item has a parent-child disagreement: the folder referenced by the
1099 /// item's `parentid` doesn't mention the item in its `children`, the
1100 /// `parentid` doesn't exist at all, or the item is a misparented content
1101 /// root.
1102 ByParentGuid(Index),
1103 }
1104
1105 impl ResolvedParent {
1106 fn index(&self) -> Option<Index> {
1107 match self {
1108 ResolvedParent::Root => None,
1109 ResolvedParent::ByStructure(index)
1110 | ResolvedParent::ByChildren(index)
1111 | ResolvedParent::ByParentGuid(index) => Some(*index),
1112 }
1113 }
1114 }
1115
1116 /// Detects cycles in resolved parents, using Floyd's tortoise and the hare
1117 /// algorithm. Returns the index of the entry where the cycle was detected,
1118 /// or `None` if there aren't any cycles.
1119 fn detect_cycles(parents: &[ResolvedParent]) -> Option<Index> {
1120 let mut seen = SmallBitVec::from_elem(parents.len(), false);
1121 for (entry_index, parent) in parents.iter().enumerate() {
1122 if seen[entry_index] {
1123 continue;
1124 }
1125 let mut parent_index = parent.index();
1126 let mut grandparent_index = parent.index().and_then(|index| parents[index].index());
1127 while let (Some(i), Some(j)) = (parent_index, grandparent_index) {
1128 if i == j {
1129 return Some(i);
1130 }
1131 if seen[i] || seen[j] {
1132 break;
1133 }
1134 parent_index = parent_index.and_then(|index| parents[index].index());
1135 grandparent_index = grandparent_index
1136 .and_then(|index| parents[index].index())
1137 .and_then(|index| parents[index].index());
1138 }
1139 seen.set(entry_index, true);
1140 }
1141 None
1142 }
1143
1144 /// Indicates if a tree entry's structure diverged.
1145 #[derive(Debug)]
1146 enum Divergence {
1147 /// The structure is already correct, and doesn't need to be reuploaded.
1148 Consistent,
1149
1150 /// The node has structure problems, and should be flagged for reupload
1151 /// when merging.
1152 Diverged,
1153 }
1154
1155 /// Describes a structure divergence for an item in a bookmark tree. These are
1156 /// used for logging and validation telemetry.
1157 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
1158 pub enum Problem {
1159 /// The item doesn't have a `parentid`, and isn't mentioned in any folders.
1160 Orphan,
1161
1162 /// The item is a user content root (menu, mobile, toolbar, or unfiled),
1163 /// but `parent_guid` isn't the Places root.
1164 MisparentedRoot(Vec<DivergedParent>),
1165
1166 /// The item has diverging parents. If the vector contains more than one
1167 /// `DivergedParent::ByChildren`, the item has multiple parents. If the
1168 /// vector contains a `DivergedParent::ByParentGuid`, with or without a
1169 /// `DivergedParent::ByChildren`, the item has a parent-child disagreement.
1170 DivergedParents(Vec<DivergedParent>),
1171
1172 /// The item is mentioned in a folder's `children`, but doesn't exist.
1173 MissingChild {
1174 child_guid: Guid,
1175 },
1176
1177 /// The item is mentioned in a folder's `children`, but is deleted.
1178 DeletedChild {
1179 child_guid: Guid,
1180 },
1181
1182 // This item is invalid e.g the URL is malformed
1183 InvalidItem,
1184 }
1185
1186 impl Problem {
1187 /// Returns count deltas for this problem.
1188 fn counts(&self) -> ProblemCounts {
1189 let (parents, deltas) = match self {
1190 Problem::Orphan => {
1191 return ProblemCounts {
1192 orphans: 1,
1193 ..ProblemCounts::default()
1194 }
1195 }
1196 Problem::DeletedChild { .. } => {
1197 return ProblemCounts {
1198 deleted_children: 1,
1199 ..ProblemCounts::default()
1200 }
1201 }
1202 Problem::MissingChild { .. } => {
1203 return ProblemCounts {
1204 missing_children: 1,
1205 ..ProblemCounts::default()
1206 }
1207 }
1208 // For misparented roots, or items with diverged parents, we need to
1209 // do a bit more work to determine all the problems. For example, a
1210 // toolbar root with a `parentid` pointing to a nonexistent folder,
1211 // and mentioned in the `children` of unfiled and menu has three
1212 // problems: it's a misparented root, with multiple parents, and a
1213 // missing `parentid`.
1214 Problem::MisparentedRoot(parents) => (
1215 parents,
1216 ProblemCounts {
1217 misparented_roots: 1,
1218 ..ProblemCounts::default()
1219 },
1220 ),
1221 Problem::DivergedParents(parents) => (parents, ProblemCounts::default()),
1222 Problem::InvalidItem => {
1223 return ProblemCounts {
1224 invalid_items: 1,
1225 ..ProblemCounts::default()
1226 }
1227 }
1228 };
1229 let deltas = match parents.as_slice() {
1230 // For items with different parents `by_parent_guid` and
1231 // `by_children`, report a parent-child disagreement.
1232 [DivergedParent::ByChildren(_)]
1233 | [DivergedParent::ByParentGuid(_)]
1234 | [DivergedParent::ByChildren(_), DivergedParent::ByParentGuid(_)]
1235 | [DivergedParent::ByParentGuid(_), DivergedParent::ByChildren(_)] => ProblemCounts {
1236 parent_child_disagreements: 1,
1237 ..deltas
1238 },
1239 // For items with multiple parents `by_children`, and possibly by
1240 // `by_parent_guid`, report a disagreement _and_ multiple parents.
1241 _ => ProblemCounts {
1242 multiple_parents_by_children: 1,
1243 parent_child_disagreements: 1,
1244 ..deltas
1245 },
1246 };
1247 // Count invalid or missing parents, but only once, since we're counting
1248 // the number of _items with the problem_, not the _occurrences of the
1249 // problem_. This is specifically for roots; it doesn't make sense for
1250 // other items to have multiple `parentid`s.
1251 parents.iter().fold(deltas, |deltas, parent| match parent {
1252 DivergedParent::ByChildren(_) => deltas,
1253 DivergedParent::ByParentGuid(p) => match p {
1254 DivergedParentGuid::Folder(_) => deltas,
1255 DivergedParentGuid::NonFolder(_) => {
1256 if deltas.non_folder_parent_guids > 0 {
1257 deltas
1258 } else {
1259 ProblemCounts {
1260 non_folder_parent_guids: 1,
1261 ..deltas
1262 }
1263 }
1264 }
1265 DivergedParentGuid::Deleted(_) => {
1266 if deltas.deleted_parent_guids > 0 {
1267 deltas
1268 } else {
1269 ProblemCounts {
1270 deleted_parent_guids: 1,
1271 ..deltas
1272 }
1273 }
1274 }
1275 DivergedParentGuid::Missing(_) => {
1276 if deltas.missing_parent_guids > 0 {
1277 deltas
1278 } else {
1279 ProblemCounts {
1280 missing_parent_guids: 1,
1281 ..deltas
1282 }
1283 }
1284 }
1285 },
1286 })
1287 }
1288 }
1289
1290 /// Describes where an invalid parent comes from.
1291 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
1292 pub enum DivergedParent {
1293 /// The item appears in this folder's `children`.
1294 ByChildren(Guid),
1295 /// The `parentid` references this folder.
1296 ByParentGuid(DivergedParentGuid),
1297 }
1298
1299 impl From<DivergedParentGuid> for DivergedParent {
1300 fn from(d: DivergedParentGuid) -> DivergedParent {
1301 DivergedParent::ByParentGuid(d)
1302 }
1303 }
1304
1305 impl fmt::Display for DivergedParent {
1306 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1307 match self {
1308 DivergedParent::ByChildren(parent_guid) => {
1309 write!(f, "is in children of {}", parent_guid)
1310 }
1311 DivergedParent::ByParentGuid(p) => match p {
1312 DivergedParentGuid::Folder(parent_guid) => write!(f, "has parent {}", parent_guid),
1313 DivergedParentGuid::NonFolder(parent_guid) => {
1314 write!(f, "has non-folder parent {}", parent_guid)
1315 }
1316 DivergedParentGuid::Deleted(parent_guid) => {
1317 write!(f, "has deleted parent {}", parent_guid)
1318 }
1319 DivergedParentGuid::Missing(parent_guid) => {
1320 write!(f, "has nonexistent parent {}", parent_guid)
1321 }
1322 },
1323 }
1324 }
1325 }
1326
1327 /// Describes an invalid `parentid`.
1328 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
1329 pub enum DivergedParentGuid {
1330 /// Exists and is a folder.
1331 Folder(Guid),
1332 /// Exists, but isn't a folder.
1333 NonFolder(Guid),
1334 /// Is explicitly deleted.
1335 Deleted(Guid),
1336 /// Doesn't exist at all.
1337 Missing(Guid),
1338 }
1339
1340 /// Records problems for all items in a tree.
1341 #[derive(Debug, Default)]
1342 pub struct Problems(HashMap<Guid, Vec<Problem>>);
1343
1344 impl Problems {
1345 /// Notes a problem for an item.
1346 #[inline]
1347 pub fn note(&mut self, guid: &Guid, problem: Problem) -> &mut Problems {
1348 self.0.entry(guid.clone()).or_default().push(problem);
1349 self
1350 }
1351
1352 /// Returns `true` if there are no problems.
1353 #[inline]
1354 pub fn is_empty(&self) -> bool {
1355 self.0.is_empty()
1356 }
1357
1358 /// Returns an iterator for all problems.
1359 pub fn summarize(&self) -> impl Iterator<Item = ProblemSummary<'_>> {
1360 self.0.iter().flat_map(|(guid, problems)| {
1361 problems
1362 .iter()
1363 .map(move |problem| ProblemSummary(guid, problem))
1364 })
1365 }
1366
1367 /// Returns total counts for each problem. If any counts are not 0, the
1368 /// tree structure diverged.
1369 pub fn counts(&self) -> ProblemCounts {
1370 self.0
1371 .values()
1372 .flatten()
1373 .fold(ProblemCounts::default(), |totals, problem| {
1374 totals.add(problem.counts())
1375 })
1376 }
1377 }
1378
1379 /// A printable summary of a problem for an item.
1380 #[derive(Clone, Copy, Debug)]
1381 pub struct ProblemSummary<'a>(&'a Guid, &'a Problem);
1382
1383 impl<'a> ProblemSummary<'a> {
1384 #[inline]
1385 pub fn guid(&self) -> &Guid {
1386 &self.0
1387 }
1388
1389 #[inline]
1390 pub fn problem(&self) -> &Problem {
1391 &self.1
1392 }
1393 }
1394
1395 impl<'a> fmt::Display for ProblemSummary<'a> {
1396 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1397 let parents = match self.problem() {
1398 Problem::Orphan => return write!(f, "{} is an orphan", self.guid()),
1399 Problem::MisparentedRoot(parents) => {
1400 write!(f, "{} is a user content root", self.guid())?;
1401 if parents.is_empty() {
1402 return Ok(());
1403 }
1404 f.write_str(", but ")?;
1405 parents
1406 }
1407 Problem::DivergedParents(parents) => {
1408 if parents.is_empty() {
1409 return write!(f, "{} has diverged parents", self.guid());
1410 }
1411 write!(f, "{} ", self.guid())?;
1412 parents
1413 }
1414 Problem::MissingChild { child_guid } => {
1415 return write!(f, "{} has nonexistent child {}", self.guid(), child_guid);
1416 }
1417 Problem::DeletedChild { child_guid } => {
1418 return write!(f, "{} has deleted child {}", self.guid(), child_guid);
1419 }
1420 Problem::InvalidItem => return write!(f, "{} is invalid", self.guid()),
1421 };
1422 match parents.as_slice() {
1423 [a] => write!(f, "{}", a)?,
1424 [a, b] => write!(f, "{} and {}", a, b)?,
1425 _ => {
1426 for (i, parent) in parents.iter().enumerate() {
1427 if i != 0 {
1428 f.write_str(", ")?;
1429 }
1430 if i == parents.len() - 1 {
1431 f.write_str("and ")?;
1432 }
1433 write!(f, "{}", parent)?;
1434 }
1435 }
1436 }
1437 Ok(())
1438 }
1439 }
1440
1441 /// Records total problem counts for telemetry. An item can have multiple
1442 /// problems, but each problem is only counted once per item.
1443 #[derive(Clone, Copy, Default, Debug, Eq, Hash, PartialEq)]
1444 pub struct ProblemCounts {
1445 /// Number of items that aren't mentioned in any parent's `children` and
1446 /// don't have a `parentid`. These are very rare; it's likely that a
1447 /// problem child has at least a `parentid`.
1448 pub orphans: usize,
1449 /// Number of roots that aren't children of the Places root.
1450 pub misparented_roots: usize,
1451 /// Number of items with multiple, conflicting parents `by_children`.
1452 pub multiple_parents_by_children: usize,
1453 /// Number of items whose `parentid` is deleted.
1454 pub deleted_parent_guids: usize,
1455 /// Number of items whose `parentid` doesn't exist.
1456 pub missing_parent_guids: usize,
1457 /// Number of items whose `parentid` isn't a folder.
1458 pub non_folder_parent_guids: usize,
1459 /// Number of items whose `parentid`s disagree with their parents'
1460 /// `children`.
1461 pub parent_child_disagreements: usize,
1462 /// Number of deleted items mentioned in all parents' `children`.
1463 pub deleted_children: usize,
1464 /// Number of nonexistent items mentioned in all parents' `children`.
1465 pub missing_children: usize,
1466 // Number of items with malformed URLs
1467 pub invalid_items: usize,
1468 }
1469
1470 impl ProblemCounts {
1471 /// Adds two sets of counts together.
1472 pub fn add(&self, other: ProblemCounts) -> ProblemCounts {
1473 ProblemCounts {
1474 orphans: self.orphans + other.orphans,
1475 misparented_roots: self.misparented_roots + other.misparented_roots,
1476 multiple_parents_by_children: self.multiple_parents_by_children
1477 + other.multiple_parents_by_children,
1478 deleted_parent_guids: self.deleted_parent_guids + other.deleted_parent_guids,
1479 missing_parent_guids: self.missing_parent_guids + other.missing_parent_guids,
1480 non_folder_parent_guids: self.non_folder_parent_guids + other.non_folder_parent_guids,
1481 parent_child_disagreements: self.parent_child_disagreements
1482 + other.parent_child_disagreements,
1483 deleted_children: self.deleted_children + other.deleted_children,
1484 missing_children: self.missing_children + other.missing_children,
1485 invalid_items: self.invalid_items + other.invalid_items,
1486 }
1487 }
1488 }
1489
1490 /// A node in a bookmark tree that knows its parent and children, and
1491 /// dereferences to its item.
1492 #[derive(Clone, Copy, Debug)]
1493 pub struct Node<'t>(&'t Tree, &'t TreeEntry);
1494
1495 impl<'t> Node<'t> {
1496 /// Returns the item for this node.
1497 #[inline]
1498 pub fn item(&self) -> &'t Item {
1499 &self.1.item
1500 }
1501
1502 /// Returns content info for deduping this item, if available.
1503 #[inline]
1504 pub fn content(&self) -> Option<&'t Content> {
1505 self.1.content.as_ref()
1506 }
1507
1508 /// Returns an iterator for all children of this node.
1509 pub fn children<'n>(&'n self) -> impl Iterator<Item = Node<'t>> + 'n {
1510 self.1
1511 .child_indices
1512 .iter()
1513 .map(move |&child_index| Node(self.0, &self.0.entries[child_index]))
1514 }
1515
1516 /// Returns the child at the given index, or `None` if the index is out of
1517 /// bounds.
1518 pub fn child(&self, index: usize) -> Option<Node<'_>> {
1519 self.1
1520 .child_indices
1521 .get(index)
1522 .map(|&child_index| Node(self.0, &self.0.entries[child_index]))
1523 }
1524
1525 /// Returns `true` if this and `other` have the same child GUIDs.
1526 pub fn has_matching_children<'u>(&self, other: Node<'u>) -> bool {
1527 if self.1.child_indices.len() != other.1.child_indices.len() {
1528 return false;
1529 }
1530 for (index, &child_index) in self.1.child_indices.iter().enumerate() {
1531 let guid = &self.0.entries[child_index].item.guid;
1532 let other_guid = &other.0.entries[other.1.child_indices[index]].item.guid;
1533 if guid != other_guid {
1534 return false;
1535 }
1536 }
1537 true
1538 }
1539
1540 /// Returns the resolved parent of this node, or `None` if this is the
1541 /// root node.
1542 pub fn parent(&self) -> Option<Node<'_>> {
1543 self.1
1544 .parent_index
1545 .as_ref()
1546 .map(|&parent_index| Node(self.0, &self.0.entries[parent_index]))
1547 }
1548
1549 /// Returns the level of this node in the tree.
1550 pub fn level(&self) -> i64 {
1551 if self.is_root() {
1552 return 0;
1553 }
1554 self.parent().map_or(-1, |parent| parent.level() + 1)
1555 }
1556
1557 /// Indicates if this node is for a syncable item.
1558 ///
1559 /// Syncable items descend from the four user content roots. For historical
1560 /// reasons, the Desktop tags root and its descendants are also marked as
1561 /// syncable, even though they are not part of the synced tree structure.
1562 /// Any other roots and their descendants, like the left pane root,
1563 /// left pane queries, and custom roots, are non-syncable.
1564 ///
1565 /// Newer Desktops should never reupload non-syncable items
1566 /// (bug 1274496), and should have removed them in Places
1567 /// migrations (bug 1310295). However, these items may be
1568 /// reparented locally to unfiled, in which case they're seen as
1569 /// syncable. If the remote tree has the missing parents
1570 /// and roots, we'll determine that the items are non-syncable
1571 /// when merging, remove them locally, and mark them for deletion
1572 /// remotely.
1573 pub fn is_syncable(&self) -> bool {
1574 if self.is_root() {
1575 return false;
1576 }
1577 if self.is_built_in_root() {
1578 return true;
1579 }
1580 match self.kind {
1581 // Exclude livemarks (bug 1477671).
1582 Kind::Livemark => false,
1583 // Exclude orphaned Places queries (bug 1433182).
1584 Kind::Query if self.diverged() => false,
1585 _ => self.parent().map_or(false, |parent| parent.is_syncable()),
1586 }
1587 }
1588
1589 /// Indicates if this node's structure diverged because it
1590 /// existed in multiple parents, or was reparented.
1591 #[inline]
1592 pub fn diverged(&self) -> bool {
1593 match &self.1.divergence {
1594 Divergence::Diverged => true,
1595 Divergence::Consistent => false,
1596 }
1597 }
1598
1599 /// Returns an ASCII art (with emoji!) representation of this node and all
1600 /// its descendants. Handy for logging.
1601 pub fn to_ascii_string(&self) -> String {
1602 self.to_ascii_fragment("")
1603 }
1604
1605 fn to_ascii_fragment(&self, prefix: &str) -> String {
1606 match self.item().kind {
1607 Kind::Folder => {
1608 let children_prefix = format!("{}| ", prefix);
1609 let children = self
1610 .children()
1611 .map(|n| n.to_ascii_fragment(&children_prefix))
1612 .collect::<Vec<String>>();
1613 let kind = if self.diverged() {
1614 "❗️📂"
1615 } else {
1616 "📂"
1617 };
1618 if children.is_empty() {
1619 format!("{}{} {}", prefix, kind, self.item())
1620 } else {
1621 format!(
1622 "{}{} {}\n{}",
1623 prefix,
1624 kind,
1625 self.item(),
1626 children.join("\n")
1627 )
1628 }
1629 }
1630 _ => {
1631 let kind = if self.diverged() {
1632 "❗️🔖"
1633 } else {
1634 "🔖"
1635 };
1636 format!("{}{} {}", prefix, kind, self.item())
1637 }
1638 }
1639 }
1640
1641 /// Indicates if this node is the root node.
1642 #[inline]
1643 pub fn is_root(&self) -> bool {
1644 ptr::eq(self.1, &self.0.entries[0])
1645 }
1646
1647 /// Indicates if this node is a Places built-in root. Any other roots except
1648 /// these are non-syncable.
1649 #[inline]
1650 pub fn is_built_in_root(&self) -> bool {
1651 self.item().guid.is_built_in_root()
1652 }
1653 }
1654
1655 impl<'t> Deref for Node<'t> {
1656 type Target = Item;
1657
1658 #[inline]
1659 fn deref(&self) -> &Item {
1660 self.item()
1661 }
1662 }
1663
1664 impl<'t> fmt::Display for Node<'t> {
1665 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1666 self.item().fmt(f)
1667 }
1668 }
1669
1670 /// An item in a local or remote bookmark tree.
1671 #[derive(Clone, Debug, Eq, PartialEq)]
1672 pub struct Item {
1673 pub guid: Guid,
1674 pub kind: Kind,
1675 pub age: i64,
1676 pub needs_merge: bool,
1677 pub validity: Validity,
1678 }
1679
1680 impl Item {
1681 /// Creates an item with the given kind.
1682 #[inline]
1683 pub fn new(guid: Guid, kind: Kind) -> Item {
1684 Item {
1685 guid,
1686 kind,
1687 age: 0,
1688 needs_merge: false,
1689 validity: Validity::Valid,
1690 }
1691 }
1692
1693 /// Indicates if the item is a folder. Only folders are allowed to have
1694 /// children.
1695 #[inline]
1696 pub fn is_folder(&self) -> bool {
1697 self.kind == Kind::Folder
1698 }
1699
1700 /// Indicates if the item can be merged with another item. Only items with
1701 /// compatible kinds can be merged.
1702 #[inline]
1703 pub fn has_compatible_kind(&self, remote_node: &Item) -> bool {
1704 match (&self.kind, &remote_node.kind) {
1705 // Bookmarks and queries are interchangeable, as simply changing the URL
1706 // can cause it to flip kinds.
1707 (Kind::Bookmark, Kind::Query) => true,
1708 (Kind::Query, Kind::Bookmark) => true,
1709 (local_kind, remote_kind) => local_kind == remote_kind,
1710 }
1711 }
1712 }
1713
1714 impl fmt::Display for Item {
1715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1716 let kind = match self.validity {
1717 Validity::Valid => format!("{}", self.kind),
1718 Validity::Reupload | Validity::Replace => format!("{} ({})", self.kind, self.validity),
1719 };
1720 let info = if self.needs_merge {
1721 format!("{}; Age = {}ms; Unmerged", kind, self.age)
1722 } else {
1723 format!("{}; Age = {}ms", kind, self.age)
1724 };
1725 write!(f, "{} ({})", self.guid, info)
1726 }
1727 }
1728
1729 /// Synced item kinds. Each corresponds to a Sync record type.
1730 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1731 pub enum Kind {
1732 Bookmark,
1733 Query,
1734 Folder,
1735 Livemark,
1736 Separator,
1737 }
1738
1739 impl fmt::Display for Kind {
1740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1741 fmt::Debug::fmt(self, f)
1742 }
1743 }
1744
1745 /// Synced item validity.
1746 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1747 pub enum Validity {
1748 /// The item is valid, and can be applied as-is.
1749 Valid,
1750
1751 /// The item can be applied, but should also be flagged for reupload. Places
1752 /// uses this to rewrite legacy tag queries.
1753 Reupload,
1754
1755 /// The item isn't valid at all, and should either be replaced with a valid
1756 /// local copy, or deleted if a valid local copy doesn't exist. Places uses
1757 /// this to flag bookmarks and queries without valid URLs.
1758 Replace,
1759 }
1760
1761 impl fmt::Display for Validity {
1762 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1763 fmt::Debug::fmt(self, f)
1764 }
1765 }
1766
1767 /// A merged bookmark node that indicates which side to prefer, and holds merged
1768 /// child nodes.
1769 #[derive(Debug)]
1770 pub struct MergedNode<'t> {
1771 pub guid: Guid,
1772 pub merge_state: MergeState<'t>,
1773 pub merged_children: Vec<MergedNode<'t>>,
1774 }
1775
1776 impl<'t> MergedNode<'t> {
1777 /// Creates a merged node from the given merge state.
1778 pub fn new(guid: Guid, merge_state: MergeState<'t>) -> MergedNode<'t> {
1779 MergedNode {
1780 guid,
1781 merge_state,
1782 merged_children: Vec::new(),
1783 }
1784 }
1785
1786 /// Indicates if the merged node exists locally and has a new GUID.
1787 /// The merger uses this to flag deduped items and items with invalid
1788 /// GUIDs with new local structure.
1789 pub fn local_guid_changed(&self) -> bool {
1790 self.merge_state
1791 .local_node()
1792 .map_or(false, |local_node| local_node.guid != self.guid)
1793 }
1794
1795 /// Indicates if the merged node exists remotely and has a new GUID. The
1796 /// merger uses this to flag parents and children of remote nodes with
1797 /// invalid GUIDs for reupload.
1798 pub fn remote_guid_changed(&self) -> bool {
1799 self.merge_state
1800 .remote_node()
1801 .map_or(false, |remote_node| remote_node.guid != self.guid)
1802 }
1803
1804 /// Returns an ASCII art representation of the root and its descendants,
1805 /// similar to `Node::to_ascii_string`.
1806 #[inline]
1807 pub fn to_ascii_string(&self) -> String {
1808 self.to_ascii_fragment("")
1809 }
1810
1811 fn to_ascii_fragment(&self, prefix: &str) -> String {
1812 match self.merge_state.node().kind {
1813 Kind::Folder => {
1814 let children_prefix = format!("{}| ", prefix);
1815 let children = self
1816 .merged_children
1817 .iter()
1818 .map(|n| n.to_ascii_fragment(&children_prefix))
1819 .collect::<Vec<String>>();
1820 if children.is_empty() {
1821 format!("{}📂 {}", prefix, &self)
1822 } else {
1823 format!("{}📂 {}\n{}", prefix, &self, children.join("\n"))
1824 }
1825 }
1826 _ => format!("{}🔖 {}", prefix, &self),
1827 }
1828 }
1829 }
1830
1831 impl<'t> fmt::Display for MergedNode<'t> {
1832 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1833 write!(f, "{} {}", self.guid, self.merge_state)
1834 }
1835 }
1836
1837 /// The merge state indicates which side we should prefer, local or remote, when
1838 /// resolving conflicts.
1839 #[derive(Clone, Copy, Debug)]
1840 pub enum MergeState<'t> {
1841 /// A local-only merge state means the item only exists locally, and should
1842 /// be uploaded.
1843 LocalOnly(Node<'t>),
1844
1845 /// Local-only with a new local structure means the item should be uploaded,
1846 /// _and_ has new children (reparented or repositioned) locally.
1847 LocalOnlyWithNewLocalStructure(Node<'t>),
1848
1849 /// A remote-only merge state means the item only exists remotely, and
1850 /// should be applied.
1851 RemoteOnly(Node<'t>),
1852
1853 /// Remote-only with a new remote structure means the item should be
1854 /// applied, _and_ has a new child list that should be uploaded.
1855 RemoteOnlyWithNewRemoteStructure(Node<'t>),
1856
1857 /// A local merge state means the item exists on both sides, and has newer
1858 /// local changes that should be uploaded.
1859 Local {
1860 local_node: Node<'t>,
1861 remote_node: Node<'t>,
1862 },
1863
1864 /// Local with a new local structure means the item has newer local changes
1865 /// that should be uploaded, and new children locally.
1866 LocalWithNewLocalStructure {
1867 local_node: Node<'t>,
1868 remote_node: Node<'t>,
1869 },
1870
1871 /// A remote merge state means the item exists on both sides, and has newer
1872 /// remote changes that should be applied.
1873 Remote {
1874 local_node: Node<'t>,
1875 remote_node: Node<'t>,
1876 },
1877
1878 /// Remote with a new remote structure means the item has newer remote
1879 /// changes that should be applied, and a new child list that should be
1880 /// uploaded.
1881 RemoteWithNewRemoteStructure {
1882 local_node: Node<'t>,
1883 remote_node: Node<'t>,
1884 },
1885
1886 /// An unchanged merge state means the item and its children are the
1887 /// same on both sides, and don't need to be uploaded or applied.
1888 Unchanged {
1889 local_node: Node<'t>,
1890 remote_node: Node<'t>,
1891 },
1892
1893 /// Unchanged with a new local structure means the item hasn't changed, but
1894 /// its children have. The new children should be applied locally, but not
1895 /// uploaded.
1896 UnchangedWithNewLocalStructure {
1897 local_node: Node<'t>,
1898 remote_node: Node<'t>,
1899 },
1900 }
1901
1902 impl<'t> MergeState<'t> {
1903 /// Returns the local node for the item, or `None` if the item only exists
1904 /// remotely. The inverse of `remote_node()`.
1905 pub fn local_node(&self) -> Option<&Node<'t>> {
1906 match self {
1907 MergeState::LocalOnly(local_node)
1908 | MergeState::LocalOnlyWithNewLocalStructure(local_node)
1909 | MergeState::Local { local_node, .. }
1910 | MergeState::LocalWithNewLocalStructure { local_node, .. }
1911 | MergeState::Remote { local_node, .. }
1912 | MergeState::RemoteWithNewRemoteStructure { local_node, .. }
1913 | MergeState::Unchanged { local_node, .. }
1914 | MergeState::UnchangedWithNewLocalStructure { local_node, .. } => Some(local_node),
1915 MergeState::RemoteOnly(_) | MergeState::RemoteOnlyWithNewRemoteStructure(_) => None,
1916 }
1917 }
1918
1919 /// Returns the remote node for the item, or `None` if the node only exists
1920 /// locally. The inverse of `local_node()`.
1921 pub fn remote_node(&self) -> Option<&Node<'t>> {
1922 match self {
1923 MergeState::Local { remote_node, .. }
1924 | MergeState::LocalWithNewLocalStructure { remote_node, .. }
1925 | MergeState::RemoteOnly(remote_node)
1926 | MergeState::RemoteOnlyWithNewRemoteStructure(remote_node)
1927 | MergeState::Remote { remote_node, .. }
1928 | MergeState::RemoteWithNewRemoteStructure { remote_node, .. }
1929 | MergeState::Unchanged { remote_node, .. }
1930 | MergeState::UnchangedWithNewLocalStructure { remote_node, .. } => Some(remote_node),
1931 MergeState::LocalOnly(_) | MergeState::LocalOnlyWithNewLocalStructure(_) => None,
1932 }
1933 }
1934
1935 /// Returns `true` if the remote item should be inserted into or updated
1936 /// in the local tree. This is not necessarily the inverse of
1937 /// `should_upload()`, as remote items with new structure should be both
1938 /// applied and reuploaded, and unchanged items should be neither.
1939 pub fn should_apply_item(&self) -> bool {
1940 match self {
1941 MergeState::RemoteOnly(_)
1942 | MergeState::RemoteOnlyWithNewRemoteStructure(_)
1943 | MergeState::Remote { .. }
1944 | MergeState::RemoteWithNewRemoteStructure { .. } => true,
1945 MergeState::LocalOnly(_)
1946 | MergeState::LocalOnlyWithNewLocalStructure(_)
1947 | MergeState::Local { .. }
1948 | MergeState::LocalWithNewLocalStructure { .. }
1949 | MergeState::Unchanged { .. }
1950 | MergeState::UnchangedWithNewLocalStructure { .. } => false,
1951 }
1952 }
1953
1954 /// Returns `true` if the item has a new structure (parent or children)
1955 /// that should be updated in the local tree.
1956 pub fn should_apply_structure(&self) -> bool {
1957 match self {
1958 MergeState::LocalOnlyWithNewLocalStructure(_)
1959 | MergeState::LocalWithNewLocalStructure { .. }
1960 | MergeState::RemoteOnly(_)
1961 | MergeState::RemoteOnlyWithNewRemoteStructure(_)
1962 | MergeState::Remote { .. }
1963 | MergeState::RemoteWithNewRemoteStructure { .. }
1964 | MergeState::UnchangedWithNewLocalStructure { .. } => true,
1965 MergeState::LocalOnly(_) | MergeState::Local { .. } | MergeState::Unchanged { .. } => {
1966 false
1967 }
1968 }
1969 }
1970
1971 /// Returns `true` if the item should be flagged for (re)upload.
1972 pub fn should_upload(&self) -> bool {
1973 match self {
1974 MergeState::LocalOnly(_)
1975 | MergeState::LocalOnlyWithNewLocalStructure(_)
1976 | MergeState::Local { .. }
1977 | MergeState::LocalWithNewLocalStructure { .. }
1978 | MergeState::RemoteOnlyWithNewRemoteStructure(_)
1979 | MergeState::RemoteWithNewRemoteStructure { .. } => true,
1980 MergeState::RemoteOnly(_)
1981 | MergeState::Remote { .. }
1982 | MergeState::Unchanged { .. }
1983 | MergeState::UnchangedWithNewLocalStructure { .. } => false,
1984 }
1985 }
1986
1987 /// Returns a new merge state, indicating that the item has a new merged
1988 /// structure that should be applied locally.
1989 pub fn with_new_local_structure(self) -> MergeState<'t> {
1990 match self {
1991 MergeState::LocalOnly(local_node) => {
1992 MergeState::LocalOnlyWithNewLocalStructure(local_node)
1993 }
1994 MergeState::LocalOnlyWithNewLocalStructure(local_node) => {
1995 MergeState::LocalOnlyWithNewLocalStructure(local_node)
1996 }
1997 MergeState::Local {
1998 local_node,
1999 remote_node,
2000 } => MergeState::LocalWithNewLocalStructure {
2001 local_node,
2002 remote_node,
2003 },
2004 MergeState::LocalWithNewLocalStructure {
2005 local_node,
2006 remote_node,
2007 } => MergeState::LocalWithNewLocalStructure {
2008 local_node,
2009 remote_node,
2010 },
2011 MergeState::RemoteOnly(remote_node) => MergeState::RemoteOnly(remote_node),
2012 MergeState::RemoteOnlyWithNewRemoteStructure(local_node) => {
2013 MergeState::RemoteOnlyWithNewRemoteStructure(local_node)
2014 }
2015 MergeState::Remote {
2016 local_node,
2017 remote_node,
2018 } => MergeState::Remote {
2019 local_node,
2020 remote_node,
2021 },
2022 MergeState::RemoteWithNewRemoteStructure {
2023 local_node,
2024 remote_node,
2025 } => MergeState::RemoteWithNewRemoteStructure {
2026 local_node,
2027 remote_node,
2028 },
2029 MergeState::Unchanged {
2030 local_node,
2031 remote_node,
2032 } => {
2033 // Once the structure changes, it doesn't matter which side we
2034 // pick; we'll need to reupload the item to the server, anyway.
2035 MergeState::UnchangedWithNewLocalStructure {
2036 local_node,
2037 remote_node,
2038 }
2039 }
2040 MergeState::UnchangedWithNewLocalStructure {
2041 local_node,
2042 remote_node,
2043 } => MergeState::UnchangedWithNewLocalStructure {
2044 local_node,
2045 remote_node,
2046 },
2047 }
2048 }
2049
2050 /// Returns a new merge state, indicating that the item has a new merged
2051 /// structure that should be reuploaded to the server.
2052 pub fn with_new_remote_structure(self) -> MergeState<'t> {
2053 match self {
2054 MergeState::LocalOnly(local_node) => MergeState::LocalOnly(local_node),
2055 MergeState::LocalOnlyWithNewLocalStructure(local_node) => {
2056 MergeState::LocalOnlyWithNewLocalStructure(local_node)
2057 }
2058 MergeState::Local {
2059 local_node,
2060 remote_node,
2061 } => MergeState::Local {
2062 local_node,
2063 remote_node,
2064 },
2065 MergeState::LocalWithNewLocalStructure {
2066 local_node,
2067 remote_node,
2068 } => MergeState::LocalWithNewLocalStructure {
2069 local_node,
2070 remote_node,
2071 },
2072 MergeState::RemoteOnly(remote_node) => {
2073 MergeState::RemoteOnlyWithNewRemoteStructure(remote_node)
2074 }
2075 MergeState::RemoteOnlyWithNewRemoteStructure(remote_node) => {
2076 MergeState::RemoteOnlyWithNewRemoteStructure(remote_node)
2077 }
2078 MergeState::Remote {
2079 local_node,
2080 remote_node,
2081 } => MergeState::RemoteWithNewRemoteStructure {
2082 local_node,
2083 remote_node,
2084 },
2085 MergeState::RemoteWithNewRemoteStructure {
2086 local_node,
2087 remote_node,
2088 } => MergeState::RemoteWithNewRemoteStructure {
2089 local_node,
2090 remote_node,
2091 },
2092 MergeState::Unchanged {
2093 local_node,
2094 remote_node,
2095 } => {
2096 // Once the structure changes, it doesn't matter which side we
2097 // pick; we'll need to reupload the item to the server, anyway.
2098 MergeState::Local {
2099 local_node,
2100 remote_node,
2101 }
2102 }
2103 MergeState::UnchangedWithNewLocalStructure {
2104 local_node,
2105 remote_node,
2106 } => MergeState::LocalWithNewLocalStructure {
2107 local_node,
2108 remote_node,
2109 },
2110 }
2111 }
2112
2113 /// Returns the node from the preferred side. Unlike `local_node()` and
2114 /// `remote_node()`, this doesn't indicate which side, so it's only used
2115 /// for logging and `try_from()`.
2116 fn node(&self) -> &Node<'t> {
2117 match self {
2118 MergeState::LocalOnly(local_node)
2119 | MergeState::LocalOnlyWithNewLocalStructure(local_node)
2120 | MergeState::Local { local_node, .. }
2121 | MergeState::LocalWithNewLocalStructure { local_node, .. }
2122 | MergeState::Unchanged { local_node, .. }
2123 | MergeState::UnchangedWithNewLocalStructure { local_node, .. } => local_node,
2124 MergeState::RemoteOnly(remote_node)
2125 | MergeState::RemoteOnlyWithNewRemoteStructure(remote_node)
2126 | MergeState::Remote { remote_node, .. }
2127 | MergeState::RemoteWithNewRemoteStructure { remote_node, .. } => remote_node,
2128 }
2129 }
2130 }
2131
2132 impl<'t> fmt::Display for MergeState<'t> {
2133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2134 f.write_str(match self {
2135 MergeState::LocalOnly(_) | MergeState::Local { .. } => "(Local, Local)",
2136 MergeState::LocalOnlyWithNewLocalStructure(_)
2137 | MergeState::LocalWithNewLocalStructure { .. } => "(Local, New)",
2138
2139 MergeState::RemoteOnly(_) | MergeState::Remote { .. } => "(Remote, Remote)",
2140 MergeState::RemoteOnlyWithNewRemoteStructure(_)
2141 | MergeState::RemoteWithNewRemoteStructure { .. } => "(Remote, New)",
2142
2143 MergeState::Unchanged { .. } => "(Unchanged, Unchanged)",
2144 MergeState::UnchangedWithNewLocalStructure { .. } => "(Unchanged, New)",
2145 })
2146 }
2147 }
2148
2149 /// Content info for an item in the local or remote tree. This is used to dedupe
2150 /// new local items to remote items that don't exist locally, with different
2151 /// GUIDs and similar content.
2152 ///
2153 /// - Bookmarks must have the same title and URL.
2154 /// - Queries must have the same title and query URL.
2155 /// - Folders and livemarks must have the same title.
2156 /// - Separators must have the same position within their parents.
2157 #[derive(Debug, Eq, Hash, PartialEq)]
2158 pub enum Content {
2159 Bookmark { title: String, url_href: String },
2160 Folder { title: String },
2161 Separator,
2162 }