aboutsummaryrefslogtreecommitdiffstats
path: root/src/swarm/set.rs
blob: 82158bee6108b1d9ff8bbba4aeef4170a37fcf2a (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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
//! Passing a set of events on between nodes (`docs/document.md`, A set of events): the
//! swarm's side of `federation::store::passing`, for a node whose store a set carries
//! (`Holding::carrying`).
//!
//! * Where the node stands goes in its STATUSes, keepalives and their replies, as
//!   another kind's stamp (`HeadsSummary::Kind`); a peer's is given to the set, and what
//!   the set says back goes to that peer.
//! * Everything else the set says goes as a SYNC's body (`SyncBody::Kind`).
//! * What the set took of a peer, or of this node's own, goes on at once to the node's
//!   other neighbours, as units: a neighbour that has them takes them for held.
//!
//! Nothing is kept of a peer between messages, and a message lost is nothing to repair:
//! the next keepalive says where the node stands again.

use std::time::Instant;

use tracing::debug;

use crate::federation::store::Id;
use crate::federation::store::passing::{self, Message, Took, Unit};
use crate::state::AppState;
use crate::swarm::topology;
use crate::transport::{self, HeadsSummary, ParsedMessage, SyncBody};

/// Whether `peer` holds a set of events and nothing else, as its handshakes said: with
/// such a peer, a node of both kinds syncs no Automerge document.
pub(crate) async fn holds_a_set_alone(state: &AppState, peer: &str) -> bool {
    match state.get_peer_state(peer).await {
        Some(peer_state) => {
            peer_state.lock().await.kind == Some(crate::federation::store::set::KIND)
        }
        None => false,
    }
}

/// Notes that `peer`, whose handshakes say an Automerge document, holds a set of
/// events beside it: it sent what a set says.
pub(crate) async fn holds_one_beside(state: &AppState, peer: &str) {
    if let Some(peer_state) = state.get_peer_state(peer).await {
        let mut peer_state = peer_state.lock().await;
        if peer_state.kind == Some(crate::document::KIND) {
            peer_state.set_beside = true;
        }
    }
}

/// On a node of both kinds, says to `peer`, whose handshakes say an Automerge
/// document, where this node's set stands, beside the STATUS that says where its
/// document does: a node of both kinds takes it, answers what its own set lacks or
/// has more of, and passes its set on to this node from then on; a node on the
/// document alone drops it. So what sets alone hold, the members' entries, crosses
/// between nodes of both kinds too.
pub(crate) async fn say_beside(state: &AppState, peer: &str) {
    if !state.holding.has_a_set() || state.holding.of_a_set() {
        return;
    }
    let of_a_document = match state.get_peer_state(peer).await {
        Some(peer_state) => peer_state.lock().await.kind == Some(crate::document::KIND),
        None => false,
    };
    if !of_a_document {
        return;
    }
    if let Some(stamp) = state.holding.with_set(passing::stamp) {
        send(state, peer, &Message::Stamp(stamp)).await;
    }
}

/// Whether `peer` holds a set of events, as its handshakes said, or, beside an
/// Automerge document, as what it sent did: what a node of both
/// kinds passes its set on to. A node that holds a set alone takes handshakes of no
/// other.
pub(crate) async fn holds_a_set(state: &AppState, peer: &str) -> bool {
    match state.get_peer_state(peer).await {
        Some(peer_state) => {
            let peer_state = peer_state.lock().await;
            peer_state.kind == Some(crate::federation::store::set::KIND) || peer_state.set_beside
        }
        None => false,
    }
}

/// Where this node's set stands, as its STATUSes say it to a peer that holds one
/// (`to_a_set`); none, where the node holds no set, or the peer doesn't.
pub(crate) fn stamp(state: &AppState, to_a_set: bool) -> Option<HeadsSummary> {
    if !state.holding.has_a_set() || !(to_a_set || state.holding.of_a_set()) {
        return None;
    }
    // A node still gathering what its set begins from stands nowhere yet.
    let stamp = state
        .holding
        .with_set(|set| rmp_serde::to_vec(&passing::stamp(set)).expect("a stamp encodes"))
        .unwrap_or_default();
    Some(HeadsSummary::Kind(stamp))
}

/// What a STATUS of `peer` says, where a set carries this node's store: where the
/// peer's set stands is given to this node's, off the caller's task; and the status is
/// handed on saying this node's own stamp, so that what compares stamps for an
/// Automerge document's sake finds nothing to do.
pub(crate) fn heard_status(
    state: &AppState,
    peer: &str,
    mut remote: transport::Status,
) -> transport::Status {
    // A peer that says where a set stands holds one.
    let of_a_set = matches!(remote.heads, HeadsSummary::Kind(_));
    let Some(ours) = stamp(state, of_a_set) else {
        return remote;
    };
    if !of_a_set && !state.holding.of_a_set() {
        return remote;
    }
    if let HeadsSummary::Kind(bytes) = std::mem::replace(&mut remote.heads, ours)
        && let Ok(stamp) = rmp_serde::from_slice::<passing::Stamp>(&bytes)
    {
        let (state, peer) = (state.clone(), peer.to_owned());
        tokio::spawn(async move {
            handle(&state, &peer, Message::Stamp(stamp)).await;
        });
    }
    remote
}

/// What a SYNC of `peer` carries of its set, where a set carries this node's store.
pub(crate) async fn received(state: &AppState, peer: &str, body: Vec<u8>) {
    let message = match rmp_serde::from_slice::<Message>(&body) {
        Ok(message) => message,
        Err(error) => {
            debug!(peer = %peer, error = %error, "What a peer says of its set doesn't read");
            return;
        }
    };
    // Started with nothing: what was asked for, to begin the set from (`ask_to_start`).
    if !state.holding.start_wants().is_empty() {
        if let Message::Units(units) = message {
            let holding = std::sync::Arc::clone(&state.holding);
            let begun = tokio::task::spawn_blocking(move || holding.start_take(units))
                .await
                .unwrap_or(false);
            if begun {
                state.notify_store_changed();
                state.topology_changed.notify_one();
            } else {
                ask(state, peer).await;
            }
        }
        return;
    }
    handle(state, peer, message).await;
}

/// Asks `peer` for what this node's set begins from, where the node started with
/// nothing and still gathers it.
async fn ask(state: &AppState, peer: &str) {
    let wants = state.holding.start_wants();
    if !wants.is_empty() {
        send(state, peer, &Message::Wants(wants)).await;
    }
}

/// Asks every peer whose handshake this node took for what its set begins from, where
/// the node started with nothing and still gathers it.
pub(crate) async fn ask_to_start(state: &AppState) {
    if state.holding.start_wants().is_empty() {
        return;
    }
    for (peer, peer_state) in state.peers_snapshot().await {
        let established =
            peer_state.lock().await.hello_state == crate::state::HelloState::Established;
        if established {
            ask(state, &peer).await;
        }
    }
}

/// Gives `message` of `peer` to this node's set, sends the peer what the set says back,
/// and passes on what it took.
async fn handle(state: &AppState, peer: &str, message: Message) {
    let holding = std::sync::Arc::clone(&state.holding);
    // Taking events judges them: off the tasks that read messages.
    let made = tokio::task::spawn_blocking(move || {
        holding.change_set(|set| passing::receive(set, message, Instant::now()))
    })
    .await;
    let Ok(Some((replies, took))) = made else {
        return;
    };
    for reply in replies {
        send(state, peer, &reply).await;
    }
    pass_on(state, Some(peer), took).await;
}

/// Sends `peer` what this node's set says.
async fn send(state: &AppState, peer: &str, message: &Message) {
    let (epoch, epoch_seq) = state.epoch_stamp();
    let envelope = transport::SyncEnvelope {
        epoch: transport::EpochTag::of(epoch),
        epoch_seq,
        body: SyncBody::Kind(rmp_serde::to_vec(message).expect("a message encodes")),
        ready: state.is_ready().await && !state.is_closing(),
        writer: None,
        delivered: false,
        sent: state.clock.now_millis(),
        signatures: serde_bytes::ByteBuf::new(),
    };
    if let Err(error) = state
        .transport
        .send_message(peer, &ParsedMessage::Sync(envelope))
        .await
    {
        debug!(peer = %peer, error = %format!("{error:#}"), "Saying of our set failed");
    }
}

/// Passes on what this node's set took, of `from` or of the node's own: to its other
/// neighbours, as units; and tells what waits on the store, or on who is a member.
async fn pass_on(state: &AppState, from: Option<&str>, took: Took) {
    if took.is_empty() {
        return;
    }
    state.notify_store_changed();
    // Entries are where members are reached, and events may change who is one.
    state.topology_changed.notify_one();
    let names = took
        .events
        .iter()
        .map(|id| id.0)
        .chain(entry_names(state, &took.entries));
    let units: Vec<Unit> = state
        .holding
        .with_set(|set| names.filter_map(|name| passing::unit(set, &name)).collect())
        .unwrap_or_default();
    if units.is_empty() {
        return;
    }
    let message = Message::Units(units);
    for peer in state.active_peers_on_local_epoch().await {
        if Some(peer.as_str()) != from
            && topology::is_neighbour(state, &peer)
            && holds_a_set(state, &peer).await
        {
            send(state, &peer, &message).await;
        }
    }
}

/// The names of the entries this node's set holds of `nodes`.
fn entry_names(state: &AppState, nodes: &[String]) -> Vec<[u8; 32]> {
    state
        .holding
        .with_set(|set| {
            nodes
                .iter()
                .filter_map(|node| set.entry(node).map(|entry| entry.name()))
                .collect()
        })
        .unwrap_or_default()
}

/// Passes on events this node's set took of the node itself (the API, its own votes):
/// `taken`, by their names.
pub(crate) async fn wrote(state: &AppState, taken: Vec<Id>) {
    pass_on(
        state,
        None,
        Took {
            events: taken,
            entries: Vec::new(),
        },
    )
    .await;
}

/// Passes on this node's own entry, which its set just took.
pub(crate) async fn registered(state: &AppState) {
    pass_on(
        state,
        None,
        Took {
            events: Vec::new(),
            entries: vec![state.local_id().to_owned()],
        },
    )
    .await;
}

/// On a node of both kinds, puts its entry as the document it holds has it as its entry
/// in the set, where the two differ, and passes it on: what the node says of itself,
/// it says to the peers of either kind.
pub(crate) async fn mirror_entry(state: &AppState) {
    use crate::federation::store::entry::Entry;
    use crate::federation::store::set::Put;

    if !state.holding.has_a_set() || state.holding.of_a_set() {
        return;
    }
    let Some(key) = state.node_key.clone() else {
        return;
    };
    let node = state.local_id().to_owned();
    let own = crate::swarm::members::member_path(&node);
    let written = crate::document::view::read_path(&state.doc.read().await.doc, &own);
    let Ok(Some(serde_json::Value::Object(written))) = written else {
        return;
    };
    let put = state.holding.change_set(|set| {
        let held = set.entry(&node);
        if held.and_then(|entry| entry.value()).as_ref() == Some(&written) {
            return None;
        }
        let count = held.map_or(1, |entry| entry.count() + 1);
        Some(set.put_entry(Entry::new(
            &set.store().id(),
            &key,
            count,
            &serde_json::Value::Object(written),
        )))
    });
    if put.flatten() == Some(Put::Taken) {
        registered(state).await;
    }
}