aboutsummaryrefslogtreecommitdiffstats
path: root/src/document/events.rs
blob: 2b3a7e08c79d8c376805d7db49743e75a7a68001 (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
177
178
179
180
181
182
183
184
185
186
//! A swarm holding a store (`docs/store.md`, On Automerge): where its document holds the
//! store, and its genesis change, built byte for byte from the store's root, so that one
//! root makes one swarm.
//!
//! The genesis change writes, in this order and nothing else: the policy at its place
//! (`access::policy`), naming the fold; the swarm's ID, the root's, at `_continuum/swarm`;
//! and the root at its ID, as bytes; each making the maps on its way
//! (`store::write_path`). Its writer is the first 16 bytes of the root's ID, its time 0,
//! and it has no message.
#![allow(dead_code)]

use automerge::legacy::OpType;
use automerge::transaction::CommitOptions;
use automerge::{ObjId, ObjType, ScalarValue, Value};
use serde_json::Value as JsonValue;

use super::typed::{TimestampFormat, Val};
use super::{ActorId, Change, Document, ReadDoc, meta, store};
use crate::federation::store::Id;

/// Where the event `id` is.
pub(crate) fn event(id: &Id) -> Vec<String> {
    meta::path(&[meta::EVENTS, &id.to_string()])
}

/// The map holding the events, if `doc` holds one.
fn events_map(doc: &impl ReadDoc) -> Option<ObjId> {
    let map = |parent: &ObjId, key: &str| match doc.get(parent, key) {
        Ok(Some((Value::Object(ObjType::Map), id))) => Some(id),
        _ => None,
    };
    map(&map(&automerge::ROOT, meta::ROOT)?, meta::EVENTS)
}

/// The IDs of the events `doc` holds.
pub(crate) fn ids(doc: &impl ReadDoc) -> Vec<Id> {
    events_map(doc).map_or_else(Vec::new, |events| {
        doc.keys(&events)
            .filter_map(|key| Id::from_hex(&key))
            .collect()
    })
}

/// The bytes `doc` holds at the event `id`.
pub(crate) fn bytes(doc: &impl ReadDoc, id: &Id) -> Option<Vec<u8>> {
    match doc.get(&events_map(doc)?, id.to_string()) {
        Ok(Some((Value::Scalar(value), _))) => match value.as_ref() {
            ScalarValue::Bytes(bytes) => Some(bytes.clone()),
            _ => None,
        },
        _ => None,
    }
}

/// The policy of a swarm holding a store of the fold `fold`.
pub(crate) fn policy(fold: &str) -> JsonValue {
    serde_json::json!({"version": 2, "store": fold})
}

/// The writer of the genesis change of the store whose root is `id`.
pub(crate) fn genesis_writer(id: &Id) -> ActorId {
    ActorId::from(&id.0[..16])
}

/// The genesis change of a swarm holding a store of the fold `fold` whose root is `root`.
pub(crate) fn genesis(fold: &str, root: &[u8]) -> Change {
    let id = Id::of(root);
    let mut doc = Document::new().with_actor(genesis_writer(&id));
    let mut write = doc.transaction();
    let writes = [
        store::write_path(&mut write, &crate::access::policy::path(), &policy(fold)),
        store::write_path(
            &mut write,
            &meta::path(&[meta::SWARM]),
            &JsonValue::String(id.to_string()),
        ),
        store::write_val_path(
            &mut write,
            &event(&id),
            &Val::Scalar(ScalarValue::Bytes(root.to_vec())),
            store::Writing::sticky(TimestampFormat::default()),
        )
        .map(|_| ()),
    ];
    for written in writes {
        // Into an empty document, under paths of maps only: nothing to refuse them.
        written.expect("an empty document takes the genesis change's writes");
    }
    write.commit_with(CommitOptions::default().with_time(0));
    doc.get_changes(&[])
        .pop()
        .expect("the genesis change was just made")
}

/// A document holding the genesis change of a swarm holding a store of the fold `fold`
/// whose root is `root`, written to under a writer of its own: the genesis change's is
/// every node's, and writes nothing else.
pub(crate) fn started(fold: &str, root: &[u8]) -> anyhow::Result<Document> {
    let mut doc = Document::new();
    doc.apply_changes([genesis(fold, root)])?;
    Ok(doc.with_actor(ActorId::random()))
}

/// Whether `change` is the genesis change of the swarm holding a store of the fold `fold`
/// whose root's ID is `id`: built again from the root it holds, byte for byte the same.
pub(crate) fn is_genesis(change: &Change, fold: &str, id: &Id) -> bool {
    if !change.deps().is_empty() || *change.actor_id() != genesis_writer(id) {
        return false;
    }
    let root = super::changes::decode(change)
        .operations
        .into_iter()
        .find_map(|op| match op.action {
            OpType::Put(ScalarValue::Bytes(bytes)) if Id::of(&bytes) == *id => Some(bytes),
            _ => None,
        });
    root.is_some_and(|root| genesis(fold, &root).hash() == change.hash())
}

/// Puts `bytes` at the event `id`, held there or not, as no change of a node puts an
/// event: for tests of what a change may write.
#[cfg(test)]
pub(crate) fn put_held(doc: &mut super::Transaction<'_>, id: &Id, bytes: &[u8]) {
    use automerge::transaction::Transactable;
    let events = events_map(doc).expect("the events' map");
    doc.put(&events, id.to_string(), ScalarValue::Bytes(bytes.to_vec()))
        .expect("a put");
}

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

    const ROOT: &[u8] = b"{\"a root\":true}";

    #[test]
    fn one_root_makes_one_genesis_change() {
        let change = genesis("federation", ROOT);
        assert_eq!(change.hash(), genesis("federation", ROOT).hash());
        assert_eq!(change.timestamp(), 0);
        assert_eq!(change.message(), None);
        assert!(change.deps().is_empty());
        assert_eq!(*change.actor_id(), genesis_writer(&Id::of(ROOT)));
        assert_ne!(change.hash(), genesis("test", ROOT).hash());
        assert_ne!(change.hash(), genesis("federation", b"another root").hash());
    }

    #[test]
    fn the_genesis_change_writes_the_policy_the_swarm_and_the_root() {
        let id = Id::of(ROOT);
        let doc = started("federation", ROOT).unwrap();
        assert_ne!(doc.get_actor(), &genesis_writer(&id));
        assert_eq!(
            store::read_plain(&doc, &crate::access::policy::path()).unwrap(),
            Some(serde_json::json!({"store": "federation", "version": 2}))
        );
        assert_eq!(
            store::read_plain(&doc, &meta::path(&[meta::SWARM])).unwrap(),
            Some(JsonValue::String(id.to_string()))
        );
        assert_eq!(ids(&doc), vec![id]);
        assert_eq!(bytes(&doc, &id).as_deref(), Some(ROOT));
    }

    #[test]
    fn a_genesis_change_is_known_by_its_root() {
        let id = Id::of(ROOT);
        let change = genesis("federation", ROOT);
        assert!(is_genesis(&change, "federation", &id));
        assert!(!is_genesis(&change, "test", &id));
        assert!(!is_genesis(&change, "federation", &Id::of(b"another root")));
        // Another time, or more written: not it.
        let mut doc = Document::new().with_actor(genesis_writer(&id));
        let mut write = doc.transaction();
        store::write_val_path(
            &mut write,
            &event(&id),
            &Val::Scalar(ScalarValue::Bytes(ROOT.to_vec())),
            store::Writing::sticky(TimestampFormat::default()),
        )
        .unwrap();
        write.commit_with(CommitOptions::default().with_time(0));
        let other = doc.get_changes(&[]).pop().unwrap();
        assert!(!is_genesis(&other, "federation", &id));
    }
}