aboutsummaryrefslogtreecommitdiffstats
path: root/src/swarm/set.rs
blob: 6df78bab2afda046f1bccd09e1c5204cc518235e (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
//! 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};

/// Where this node's set stands, as its STATUSes say it; none, where no set carries its
/// store.
pub(crate) fn stamp(state: &AppState) -> Option<HeadsSummary> {
    if !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 {
    let Some(ours) = stamp(state) else {
        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) {
            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;
}