summaryrefslogtreecommitdiffstats
path: root/src/federation/revision.rs
blob: 7be6254499698626fbe9d377590e7afc7038307f (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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//! The revisions of federation 1 (`docs/federation.md`, Changing the federation): what a
//! version names of what nodes take, refuse and count beyond the base revision the
//! federation began with. Each adds a feature to those of the one before. A revision is
//! named by the SHA-256 of the JCS list of its features' names, so that a continuum that
//! doesn't know it, another build's among them, can't read a version naming it, and stops
//! there.

use std::fmt;

use super::jcs::Json;
use super::store::Id;

/// A feature a revision adds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Feature {
    /// Merge events: a node its party lists, with its own key, builds on events it holds,
    /// writing nothing (`Does::Merge`).
    MergeEvents,
}

impl Feature {
    /// Its name, in the IDs of the revisions that have it: never changed once released,
    /// and specific, so that a feature another build names alike is one it adds alike.
    pub(crate) fn name(self) -> &'static str {
        match self {
            Feature::MergeEvents => "merge-events",
        }
    }

    /// What it adds, in a line.
    pub(crate) fn what(self) -> &'static str {
        match self {
            Feature::MergeEvents => {
                "merge events, which a node its party lists signs with its own key, building \
                 on events it holds and writing nothing"
            }
        }
    }

    /// The revision that adds it.
    pub(crate) fn revision(self) -> Revision {
        let at = FEATURES
            .iter()
            .position(|feature| *feature == self)
            .expect("every feature is in FEATURES");
        Revision(at + 1)
    }
}

/// The features, in the order revisions add them: revision n has the first n, the base
/// revision none. Only ever appended to.
pub(crate) const FEATURES: &[Feature] = &[Feature::MergeEvents];

/// A revision: how many of `FEATURES` it has.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Revision(pub(crate) usize);

impl Revision {
    /// The newest this continuum knows.
    pub(crate) fn newest() -> Revision {
        Revision(FEATURES.len())
    }

    /// Every revision this continuum knows, the base revision first.
    pub(crate) fn known() -> impl Iterator<Item = Revision> {
        (0..=FEATURES.len()).map(Revision)
    }

    /// Its ID: the SHA-256 of the JCS list of its features' names.
    pub(crate) fn id(self) -> Id {
        let names = self
            .features()
            .iter()
            .map(|feature| Json::Str(feature.name().to_owned()))
            .collect();
        Id::of(&Json::Array(names).bytes())
    }

    /// The revision of ID `id`, of those this continuum knows.
    pub(crate) fn of(id: &Id) -> Option<Revision> {
        Revision::known().find(|revision| revision.id() == *id)
    }

    /// Its features.
    pub(crate) fn features(self) -> &'static [Feature] {
        &FEATURES[..self.0]
    }

    /// Whether it has `feature`.
    pub(crate) fn has(self, feature: Feature) -> bool {
        self.features().contains(&feature)
    }

    /// What this continuum knows, as people read it: "the base revision alone", or
    /// "revisions up to 2 (…)".
    pub(crate) fn knowing() -> String {
        match Revision::newest() {
            Revision(0) => "the base revision alone".to_owned(),
            newest => format!("revisions up to {} ({})", newest.0, newest.names()),
        }
    }

    /// Its features' names, as people read them.
    fn names(self) -> String {
        let names: Vec<&str> = self
            .features()
            .iter()
            .map(|feature| feature.name())
            .collect();
        names.join(", ")
    }
}

/// The revision a version's `revision` names (`named`, none for the base revision), as
/// people read it: with its ID where it names one, and where this continuum doesn't know
/// it, so said.
pub(crate) fn described(named: Option<&Json>) -> String {
    let Some(named) = named else {
        return Revision::default().to_string();
    };
    match named.as_str().and_then(Id::from_hex) {
        Some(id) => match Revision::of(&id) {
            Some(revision) => format!("{revision}, {id}"),
            None => format!("{id}, a revision this continuum doesn't know"),
        },
        None => "no revision's ID".to_owned(),
    }
}

/// As people read it: "the base revision", or "revision 2 (merge-events, …)".
impl fmt::Display for Revision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            0 => f.write_str("the base revision"),
            n => write!(f, "revision {n} ({})", self.names()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A revision's ID is the SHA-256 of the JCS list of its features' names: the base
    /// revision's, of `[]`.
    #[test]
    fn a_revision_is_named_by_its_features() {
        assert_eq!(Revision::default().id(), Id::of(b"[]"));
        assert_eq!(Revision::of(&Id::of(b"[]")), Some(Revision(0)));
        assert_eq!(Revision::of(&Id::of(b"[\"elsewhere\"]")), None);
        assert_eq!(Revision::default().to_string(), "the base revision");
        assert_eq!(
            Feature::MergeEvents.revision().to_string(),
            "revision 1 (merge-events)"
        );
        assert_eq!(
            Revision(1).id(),
            Id::of(br#"["merge-events"]"#),
            "a released revision's ID changes never"
        );
        let names: Vec<&str> = FEATURES.iter().map(|feature| feature.name()).collect();
        let distinct: std::collections::BTreeSet<&str> = names.iter().copied().collect();
        assert_eq!(distinct.len(), names.len(), "a feature named twice");
        for revision in Revision::known() {
            assert_eq!(Revision::of(&revision.id()), Some(revision));
        }
        assert_eq!(described(None), "the base revision");
        let one = Json::Str(Revision(1).id().to_string());
        assert_eq!(
            described(Some(&one)),
            format!("revision 1 (merge-events), {}", Revision(1).id())
        );
        let unknown = Json::Str(Id::of(b"elsewhere").to_string());
        assert!(described(Some(&unknown)).ends_with("a revision this continuum doesn't know"));
    }
}