aboutsummaryrefslogtreecommitdiffstats
path: root/src/document/dropping.rs
blob: 56775fd35fd394d89446e002021036376c562397 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
//! A document without a change it holds and every change built on it: what goes
//! (`Tainted`), and the document that is left (`Tainted::dropped`), forked where none of
//! them is, written by a fresh actor, as the old one's later changes are among those
//! dropped.

use std::collections::HashSet;

use super::{ActorId, Change, ChangeHash, Document, ExpandedChange};

/// Why a change isn't dropped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kept {
    /// It is the epoch's root: what the document is.
    Root,
    /// Nothing would be left.
    Nothing,
}

/// A change a document holds and all that builds on it.
pub(crate) struct Tainted {
    root: ChangeHash,
    changes: Vec<Change>,
    tainted: HashSet<ChangeHash>,
}

/// The document left once what a `Tainted` names is dropped, and what went.
pub(crate) struct Dropped {
    pub(crate) doc: Document,
    /// The fresh actor `doc` is written by.
    pub(crate) actor: ActorId,
    /// What this node's own writes among those dropped touched.
    pub(crate) own_paths: Vec<Vec<String>>,
    /// The others' changes dropped.
    pub(crate) theirs: Vec<Theirs>,
}

/// Another node's change dropped: who made it, for whom, and whether it is the one
/// dropped or builds on it.
pub(crate) struct Theirs {
    pub(crate) change: Change,
    pub(crate) committer: Option<String>,
    pub(crate) user: Option<String>,
    pub(crate) root: bool,
}

impl Tainted {
    /// `root` and what builds on it in `doc`; none if `doc` doesn't hold it; why it is
    /// kept, where it is.
    pub(crate) fn of(doc: &Document, root: ChangeHash) -> Option<Result<Tainted, Kept>> {
        let changes: Vec<Change> = doc.get_changes(&[]).into_iter().collect();
        let dropped = changes.iter().find(|change| change.hash() == root)?;
        if dropped.deps().is_empty() {
            return Some(Err(Kept::Root));
        }
        // In causal order: a change after those it builds on.
        let mut tainted: HashSet<ChangeHash> = [root].into();
        for change in &changes {
            if change.deps().iter().any(|dep| tainted.contains(dep)) {
                tainted.insert(change.hash());
            }
        }
        if tainted.len() == changes.len() {
            return Some(Err(Kept::Nothing));
        }
        Some(Ok(Tainted {
            root,
            changes,
            tainted,
        }))
    }

    /// How many changes go.
    pub(crate) fn len(&self) -> usize {
        self.tainted.len()
    }

    /// How many changes the document holds, those that go among them.
    pub(crate) fn of_all(&self) -> usize {
        self.changes.len()
    }

    /// `doc` without them: this node's own writes among them by the actors it wrote
    /// under (`own`, and the one `doc` writes with).
    pub(crate) fn dropped(self, doc: &Document, own: Vec<ActorId>) -> anyhow::Result<Dropped> {
        let kept = || {
            self.changes
                .iter()
                .filter(|change| !self.tainted.contains(&change.hash()))
        };
        let built_on: HashSet<ChangeHash> = kept()
            .flat_map(|change| change.deps().iter().copied())
            .collect();
        let heads: Vec<ChangeHash> = kept()
            .map(|change| change.hash())
            .filter(|hash| !built_on.contains(hash))
            .collect();
        let mut actors = own;
        actors.push(doc.get_actor().clone());
        let gone = || {
            self.changes
                .iter()
                .filter(|change| self.tainted.contains(&change.hash()))
        };
        let ours: Vec<ExpandedChange> = gone()
            .filter(|change| actors.contains(change.actor_id()))
            .map(|change| change.decode())
            .collect();
        let mut own_paths: Vec<Vec<String>> = super::inspect::Inspector::new(doc)
            .ops(&ours)
            .into_iter()
            .flatten()
            .map(|op| op.path)
            .collect();
        own_paths.sort();
        own_paths.dedup();
        let actor = ActorId::random();
        let fresh = doc.fork_at(&heads)?.with_actor(actor.clone());
        let theirs = gone()
            .filter(|change| !actors.contains(change.actor_id()))
            .map(|change| Theirs {
                change: change.clone(),
                committer: doc
                    .get_author_for_actor(change.actor_id())
                    .and_then(|author| {
                        std::str::from_utf8(author.as_bytes())
                            .ok()
                            .map(str::to_owned)
                    }),
                user: change
                    .message()
                    .and_then(super::replica::user_of)
                    .map(str::to_owned),
                root: change.hash() == self.root,
            })
            .collect();
        Ok(Dropped {
            doc: fresh,
            actor,
            own_paths,
            theirs,
        })
    }
}