ouisync/network/
connection.rs

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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
use super::{
    peer_addr::PeerAddr,
    peer_info::PeerInfo,
    peer_source::PeerSource,
    peer_state::PeerState,
    runtime_id::PublicRuntimeId,
    stats::{ByteCounters, StatsTracker},
};
use crate::{
    collections::{hash_map::Entry, HashMap},
    sync::{AwaitDrop, DropAwaitable, WatchSenderExt},
};
use serde::Serialize;
use std::{
    fmt,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
    time::SystemTime,
};
use tokio::sync::watch;

/// Container for known connections.
pub(super) struct ConnectionSet {
    connections: watch::Sender<HashMap<Key, Data>>,
}

impl ConnectionSet {
    pub fn new() -> Self {
        Self {
            connections: watch::Sender::new(HashMap::default()),
        }
    }

    /// Attempt to reserve an connection to the given peer. If the connection hasn't been reserved
    /// yet, it returns a `ConnectionPermit` which keeps the connection reserved as long as it
    /// lives. Otherwise it returns `None`. To release a connection the permit needs to be dropped.
    /// Also returns a notification object that can be used to wait until the permit gets released.
    pub fn reserve(&self, addr: PeerAddr, source: PeerSource) -> ReserveResult {
        let key = Key {
            addr,
            dir: ConnectionDirection::from_source(source),
        };

        self.connections
            .send_if_modified_return(|connections| match connections.entry(key) {
                Entry::Vacant(entry) => {
                    let id = ConnectionId::next();

                    entry.insert(Data {
                        id,
                        state: PeerState::Known,
                        source,
                        stats_tracker: StatsTracker::default(),
                        on_release: DropAwaitable::new(),
                    });

                    (
                        true,
                        ReserveResult::Permit(ConnectionPermit {
                            connections: self.connections.clone(),
                            key,
                            id,
                        }),
                    )
                }
                Entry::Occupied(entry) => {
                    let peer_permit = entry.get();

                    (
                        false,
                        ReserveResult::Occupied(
                            peer_permit.on_release.subscribe(),
                            peer_permit.source,
                            peer_permit.id,
                        ),
                    )
                }
            })
    }

    pub fn peer_info_collector(&self) -> PeerInfoCollector {
        PeerInfoCollector(self.connections.clone())
    }

    pub fn get_peer_info(&self, addr: PeerAddr) -> Option<PeerInfo> {
        let connections = self.connections.borrow();

        connections
            .get(&Key {
                addr,
                dir: ConnectionDirection::Incoming,
            })
            .or_else(|| {
                connections.get(&Key {
                    addr,
                    dir: ConnectionDirection::Outgoing,
                })
            })
            .map(|data| data.peer_info(addr))
    }

    pub fn subscribe(&self) -> ConnectionSetSubscription {
        ConnectionSetSubscription(self.connections.subscribe())
    }
}

/// Unique identifier of a connection. Connections are mostly already identified by the peer address
/// and direction (incoming / outgoing), but this type allows to distinguish even connections with
/// the same address/direction but that were established in two separate occasions.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
#[repr(transparent)]
pub(super) struct ConnectionId(u64);

impl ConnectionId {
    pub fn next() -> Self {
        static NEXT: AtomicU64 = AtomicU64::new(0);
        Self(NEXT.fetch_add(1, Ordering::Relaxed))
    }
}

impl fmt::Display for ConnectionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

pub(super) enum ReserveResult {
    Permit(ConnectionPermit),
    // Use the receiver to get notified when the existing permit is destroyed.
    Occupied(AwaitDrop, PeerSource, ConnectionId),
}

#[derive(Clone)]
pub struct ConnectionSetSubscription(watch::Receiver<HashMap<Key, Data>>);

impl ConnectionSetSubscription {
    pub async fn changed(&mut self) -> Result<(), watch::error::RecvError> {
        self.0.changed().await?;
        Ok(())
    }
}

#[derive(Clone)]
pub struct PeerInfoCollector(watch::Sender<HashMap<Key, Data>>);

impl PeerInfoCollector {
    pub fn collect(&self) -> Vec<PeerInfo> {
        self.0
            .borrow()
            .iter()
            .map(|(key, data)| data.peer_info(key.addr))
            .collect()
    }
}

#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize)]
pub(super) enum ConnectionDirection {
    Incoming,
    Outgoing,
}

impl ConnectionDirection {
    pub fn from_source(source: PeerSource) -> Self {
        match source {
            PeerSource::Listener => Self::Incoming,
            PeerSource::UserProvided
            | PeerSource::LocalDiscovery
            | PeerSource::Dht
            | PeerSource::PeerExchange => Self::Outgoing,
        }
    }
}

/// Connection permit that prevents another connection to the same peer (socket address) to be
/// established as long as it remains in scope.
pub(super) struct ConnectionPermit {
    connections: watch::Sender<HashMap<Key, Data>>,
    key: Key,
    id: ConnectionId,
}

impl ConnectionPermit {
    /// Split the permit into two halves where dropping any of them releases the whole permit.
    /// This is useful when the connection needs to be split into a reader and a writer Then if any
    /// of them closes, the whole connection closes. So both the reader and the writer should be
    /// associated with one half of the permit so that when any of them closes, the permit is
    /// released.
    pub fn into_split(self) -> (ConnectionPermitHalf, ConnectionPermitHalf) {
        (
            ConnectionPermitHalf(Self {
                connections: self.connections.clone(),
                key: self.key,
                id: self.id,
            }),
            ConnectionPermitHalf(self),
        )
    }

    pub fn mark_as_connecting(&self) {
        self.set_state(PeerState::Connecting);
    }

    pub fn mark_as_handshaking(&self) {
        self.set_state(PeerState::Handshaking);
    }

    pub fn mark_as_active(&self, runtime_id: PublicRuntimeId) {
        self.set_state(PeerState::Active {
            id: runtime_id,
            since: SystemTime::now(),
        });
    }

    fn set_state(&self, new_state: PeerState) {
        self.connections.send_if_modified(|connections| {
            // unwrap is ok because if `self` exists then the entry should exists as well.
            let peer = connections.get_mut(&self.key).unwrap();

            if peer.state != new_state {
                peer.state = new_state;
                true
            } else {
                false
            }
        });
    }

    /// Returns a `AwaitDrop` that gets notified when this permit gets released.
    pub fn released(&self) -> AwaitDrop {
        // We can't use unwrap here because this method is used in `ConnectionPermitHalf` which can
        // outlive the entry if the other half gets dropped.
        self.with(|data| data.on_release.subscribe())
            .unwrap_or_else(|| DropAwaitable::new().subscribe())
    }

    pub fn addr(&self) -> PeerAddr {
        self.key.addr
    }

    pub fn id(&self) -> ConnectionId {
        self.id
    }

    pub fn source(&self) -> PeerSource {
        // unwrap is ok because if `self` exists then the entry should exists as well.
        self.with(|data| data.source).unwrap()
    }

    pub fn byte_counters(&self) -> Arc<ByteCounters> {
        self.with(|data| data.stats_tracker.bytes.clone())
            .unwrap_or_default()
    }

    /// Dummy connection permit for tests.
    #[cfg(test)]
    pub fn dummy() -> Self {
        use std::net::Ipv4Addr;

        let key = Key {
            addr: PeerAddr::Tcp((Ipv4Addr::UNSPECIFIED, 0).into()),
            dir: ConnectionDirection::Incoming,
        };
        let id = ConnectionId::next();
        let data = Data {
            id,
            state: PeerState::Known,
            source: PeerSource::UserProvided,
            stats_tracker: StatsTracker::default(),
            on_release: DropAwaitable::new(),
        };

        Self {
            connections: watch::Sender::new([(key, data)].into()),
            key,
            id,
        }
    }

    fn with<F, R>(&self, f: F) -> Option<R>
    where
        F: FnOnce(&Data) -> R,
    {
        self.connections.borrow().get(&self.key).map(f)
    }
}

impl fmt::Debug for ConnectionPermit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("ConnectionPermit")
            .field("key", &self.key)
            .field("id", &self.id)
            .finish_non_exhaustive()
    }
}

impl Drop for ConnectionPermit {
    fn drop(&mut self) {
        self.connections.send_if_modified(|connections| {
            let Entry::Occupied(entry) = connections.entry(self.key) else {
                return false;
            };

            if entry.get().id != self.id {
                return false;
            }

            entry.remove();
            true
        });
    }
}

/// Half of a connection permit. Dropping it drops the whole permit.
/// See [`ConnectionPermit::split`] for more details.
pub(super) struct ConnectionPermitHalf(ConnectionPermit);

impl ConnectionPermitHalf {
    pub fn id(&self) -> ConnectionId {
        self.0.id
    }

    pub fn byte_counters(&self) -> Arc<ByteCounters> {
        self.0.byte_counters()
    }

    pub fn released(&self) -> AwaitDrop {
        self.0.released()
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct Key {
    addr: PeerAddr,
    dir: ConnectionDirection,
}

struct Data {
    id: ConnectionId,
    state: PeerState,
    source: PeerSource,
    stats_tracker: StatsTracker,
    on_release: DropAwaitable,
}

impl Data {
    fn peer_info(&self, addr: PeerAddr) -> PeerInfo {
        let stats = self.stats_tracker.read();

        PeerInfo {
            addr,
            source: self.source,
            state: self.state,
            stats,
        }
    }
}