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
#![allow(deprecated)]

use crate::{id::Id, Address, Logs, Proximity, Record, Subscription, Subscriptions};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NodeInfo {
    id: Id,
    address: Option<Address>,
}

/// The profile of the node, its [`Id`], its [`Address`] and its
/// [`Subscriptions`].
///
/// This is the information that is created and propagated by the
/// Node itself.
///
/// [`Id`]: ./struct.Id.html
/// [`Address`]: ./struct.Address.html
/// [`Subscriptions`]: ./struct.Subscriptions.html
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NodeProfile {
    info: NodeInfo,

    subscriptions: Subscriptions,
}

pub struct NodeProfileBuilder {
    id: Id,
    address: Option<Address>,
    subscriptions: Subscriptions,
}

/// Data we store about a node, this includes the [`NodeProfile`] in the
/// latest state known of, as well as any other metadata useful for operating
/// with the node.
///
/// [`NodeProfile`]: ./struct.NodeProfile.html
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Node {
    profile: NodeProfile,

    address: Address,

    logs: Logs,

    record: Record,
}

impl NodeInfo {
    pub fn address(&self) -> Option<&Address> {
        self.address.as_ref()
    }
}

impl NodeProfileBuilder {
    pub fn new() -> Self {
        Self {
            id: Id::generate(rand::thread_rng()),
            address: None,
            subscriptions: Subscriptions::default(),
        }
    }

    pub fn address(&mut self, address: Address) -> &mut Self {
        self.address = Some(address);
        self
    }

    pub fn add_subscription(&mut self, subscription: Subscription) -> &mut Self {
        self.subscriptions.insert(subscription);
        self
    }

    pub fn build(&self) -> NodeProfile {
        NodeProfile {
            info: NodeInfo {
                id: self.id,
                address: self.address.clone(),
            },
            subscriptions: self.subscriptions.clone(),
        }
    }
}

impl NodeProfile {
    pub fn address(&self) -> Option<&Address> {
        self.info.address.as_ref()
    }

    pub fn subscriptions(&self) -> &Subscriptions {
        &self.subscriptions
    }

    /// list all common subscriptions between the two nodes
    pub fn common_subscriptions<'a>(
        &'a self,
        other: &'a Self,
    ) -> impl Iterator<Item = &'a Subscription> {
        self.subscriptions
            .common_subscriptions(&other.subscriptions)
    }

    /// compute the relative proximity between these 2 nodes.
    ///
    /// This is based on the subscription. The more 2 nodes have subscription
    /// in common the _closer_ they are.
    pub fn proximity(&self, other: &Self) -> Proximity {
        self.subscriptions.proximity_to(&other.subscriptions)
    }

    pub fn check(&self) -> bool {
        // XXX: missing self validation of the data
        true
    }
}

pub enum NodeAddress {
    Discoverable(Address),
    NonDiscoverable(Address),
}

impl NodeAddress {
    pub(crate) fn is_discoverable(&self) -> bool {
        match self {
            Self::Discoverable(_address) => true,
            Self::NonDiscoverable(_address) => false,
        }
    }

    pub(crate) fn as_ref(&self) -> &Address {
        match self {
            Self::Discoverable(address) => address,
            Self::NonDiscoverable(address) => address,
        }
    }
}

impl Node {
    pub(crate) fn new(address: Address, profile: NodeProfile) -> Self {
        Self {
            profile,
            address,
            logs: Logs::default(),
            record: Record::default(),
        }
    }

    pub fn address(&self) -> &Address {
        self.profile.address().unwrap_or_else(|| &self.address)
    }

    pub fn node_address(&self) -> NodeAddress {
        self.profile()
            .address()
            .cloned()
            .map(NodeAddress::Discoverable)
            .unwrap_or_else(|| NodeAddress::NonDiscoverable(self.address.clone()))
    }

    pub fn profile(&self) -> &NodeProfile {
        &self.profile
    }

    pub(crate) fn update_gossip(&mut self, gossip: NodeProfile) {
        self.update_profile(gossip);
        self.logs_mut().updated();
    }

    fn update_profile(&mut self, profile: NodeProfile) {
        self.profile = profile;
    }

    pub fn record(&self) -> &Record {
        &self.record
    }

    pub fn record_mut(&mut self) -> &mut Record {
        &mut self.record
    }

    pub fn logs(&self) -> &Logs {
        &self.logs
    }

    pub fn logs_mut(&mut self) -> &mut Logs {
        &mut self.logs
    }
}

impl Default for NodeProfileBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use quickcheck::{Arbitrary, Gen};

    impl Arbitrary for NodeInfo {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            NodeInfo {
                id: Id::arbitrary(g),
                address: Arbitrary::arbitrary(g),
            }
        }
    }

    impl Arbitrary for NodeProfile {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            NodeProfile {
                info: NodeInfo::arbitrary(g),
                subscriptions: Subscriptions::arbitrary(g),
            }
        }
    }

    #[quickcheck]
    fn node_info_encode_decode_json(node_info: NodeInfo) -> bool {
        let encoded = serde_json::to_string(&node_info).unwrap();
        let decoded = serde_json::from_str(&encoded).unwrap();
        node_info == decoded
    }

    #[quickcheck]
    fn node_info_encode_decode_bincode(node_info: NodeInfo) -> bool {
        let encoded = bincode::serialize(&node_info).unwrap();
        let decoded = bincode::deserialize(&encoded).unwrap();
        node_info == decoded
    }

    #[quickcheck]
    fn node_profile_encode_decode_json(node_profile: NodeProfile) -> bool {
        let encoded = serde_json::to_string(&node_profile).unwrap();
        let decoded = serde_json::from_str(&encoded).unwrap();
        node_profile == decoded
    }

    #[quickcheck]
    fn node_profile_encode_decode_bincode(node_profile: NodeProfile) -> bool {
        let encoded = bincode::serialize(&node_profile).unwrap();
        let decoded = bincode::deserialize(&encoded).unwrap();
        node_profile == decoded
    }
}