Skip to content
46 changes: 6 additions & 40 deletions misc/peer-store/src/behaviour.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,8 @@
use std::{collections::VecDeque, task::Poll};

use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::{dummy, NetworkBehaviour};

use crate::store::Store;

/// Events generated by [`Behaviour`] and emitted back to [`Swarm`](libp2p_swarm::Swarm).
#[derive(Debug, Clone)]
pub enum Event<T> {
/// The peer's record has been updated.
/// Manually updating a record will always emit this event
/// even if it provides no new information.
RecordUpdated {
/// The peer that has an update.
peer: PeerId,
},
/// Event from the internal store.
Store(T),
}
Comment thread
elenaf9 marked this conversation as resolved.

/// Behaviour that maintains a peer address book.
///
/// Usage:
Expand All @@ -39,8 +23,6 @@ pub enum Event<T> {
pub struct Behaviour<S: Store> {
/// The internal store.
store: S,
/// Pending Events to be emitted back to [`Swarm`](libp2p_swarm::Swarm).
pending_events: VecDeque<Event<S::FromStore>>,
}

impl<'a, S> Behaviour<S>
Expand All @@ -49,10 +31,7 @@ where
{
/// Build a new [`Behaviour`] with the given store.
pub fn new(store: S) -> Self {
Self {
store,
pending_events: VecDeque::new(),
}
Self { store }
}

/// Try to get all observed address of the given peer.
Expand All @@ -73,24 +52,16 @@ where
pub fn store_mut(&mut self) -> &mut S {
&mut self.store
}

fn handle_store_event(&mut self, event: crate::store::Event<<S as Store>::FromStore>) {
use crate::store::Event::*;
match event {
RecordUpdated(peer) => self.pending_events.push_back(Event::RecordUpdated { peer }),
Store(ev) => self.pending_events.push_back(Event::Store(ev)),
}
}
}

impl<S> NetworkBehaviour for Behaviour<S>
where
S: Store + 'static,
<S as Store>::FromStore: Send + Sync,
<S as Store>::Event: Send + Sync,
{
type ConnectionHandler = dummy::ConnectionHandler;

type ToSwarm = Event<S::FromStore>;
type ToSwarm = S::Event;

fn handle_established_inbound_connection(
&mut self,
Expand Down Expand Up @@ -149,13 +120,8 @@ where
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<libp2p_swarm::ToSwarm<Self::ToSwarm, libp2p_swarm::THandlerInEvent<Self>>>
{
if let Some(ev) = self.store.poll(cx) {
self.handle_store_event(ev);
};

if let Some(ev) = self.pending_events.pop_front() {
return Poll::Ready(libp2p_swarm::ToSwarm::GenerateEvent(ev));
}
Poll::Pending
Comment thread
elenaf9 marked this conversation as resolved.
self.store
.poll(cx)
.map(libp2p_swarm::ToSwarm::GenerateEvent)
}
}
2 changes: 1 addition & 1 deletion misc/peer-store/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ mod behaviour;
pub mod memory_store;
mod store;

pub use behaviour::{Behaviour, Event};
pub use behaviour::Behaviour;
pub use store::Store;
Loading
Loading