Skip to content

Commit

Permalink
refactor(kad): rename to follow naming convention across repository
Browse files Browse the repository at this point in the history
Renamed the following

`kad::Kademlia` -> `kad::Behaviour`
`kad::KademliaEvent` -> `kad::Event`
`kad::KademliaBucketInserts` -> `kad::BucketInserts`
`kad::KademliaStoreInserts` -> `kad::StoreInserts`
`kad::KademliaConfig` -> `kad::Config`
`kad::KademliaCaching` -> `kad::Caching`
`kad::KademliaEvent` -> `kad::Event`
`kad::KademliaConnectionType` -> `kad::ConnectionType`
`KademliaHandler` -> `Handler`
`KademliaHandlerEvent` -> `HandlerEvent`
`KademliaProtocolConfig` -> `ProtocolConfig`
`KademliaHandlerIn` -> `HandlerIn`
`KademliaRequestId` -> `RequestId`
`KademliaHandlerQueryErr` -> `HandlerQueryErr`

Resolves: #4485

Pull-Request: #4547.
  • Loading branch information
PanGan21 authored Sep 27, 2023
1 parent fffd47b commit c8b5f49
Show file tree
Hide file tree
Showing 19 changed files with 525 additions and 530 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ libp2p-floodsub = { version = "0.43.0", path = "protocols/floodsub" }
libp2p-gossipsub = { version = "0.45.1", path = "protocols/gossipsub" }
libp2p-identify = { version = "0.43.1", path = "protocols/identify" }
libp2p-identity = { version = "0.2.3" }
libp2p-kad = { version = "0.44.5", path = "protocols/kad" }
libp2p-kad = { version = "0.44.6", path = "protocols/kad" }
libp2p-mdns = { version = "0.44.0", path = "protocols/mdns" }
libp2p-memory-connection-limits = { version = "0.1.0", path = "misc/memory-connection-limits" }
libp2p-metrics = { version = "0.13.1", path = "misc/metrics" }
Expand Down
53 changes: 25 additions & 28 deletions examples/distributed-key-value-store/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,9 @@
use async_std::io;
use futures::{prelude::*, select};
use libp2p::core::upgrade::Version;
use libp2p::kad;
use libp2p::kad::record::store::MemoryStore;
use libp2p::kad::Mode;
use libp2p::kad::{
record::Key, AddProviderOk, GetProvidersOk, GetRecordOk, Kademlia, KademliaEvent, PeerRecord,
PutRecordOk, QueryResult, Quorum, Record,
};
use libp2p::{
identity, mdns, noise,
swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent},
Expand All @@ -54,18 +51,18 @@ async fn main() -> Result<(), Box<dyn Error>> {
#[derive(NetworkBehaviour)]
#[behaviour(to_swarm = "MyBehaviourEvent")]
struct MyBehaviour {
kademlia: Kademlia<MemoryStore>,
kademlia: kad::Behaviour<MemoryStore>,
mdns: mdns::async_io::Behaviour,
}

#[allow(clippy::large_enum_variant)]
enum MyBehaviourEvent {
Kademlia(KademliaEvent),
Kademlia(kad::Event),
Mdns(mdns::Event),
}

impl From<KademliaEvent> for MyBehaviourEvent {
fn from(event: KademliaEvent) -> Self {
impl From<kad::Event> for MyBehaviourEvent {
fn from(event: kad::Event) -> Self {
MyBehaviourEvent::Kademlia(event)
}
}
Expand All @@ -80,7 +77,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let mut swarm = {
// Create a Kademlia behaviour.
let store = MemoryStore::new(local_peer_id);
let kademlia = Kademlia::new(local_peer_id, store);
let kademlia = kad::Behaviour::new(local_peer_id, store);
let mdns = mdns::async_io::Behaviour::new(mdns::Config::default(), local_peer_id)?;
let behaviour = MyBehaviour { kademlia, mdns };
SwarmBuilder::with_async_std_executor(transport, behaviour, local_peer_id).build()
Expand All @@ -107,22 +104,22 @@ async fn main() -> Result<(), Box<dyn Error>> {
swarm.behaviour_mut().kademlia.add_address(&peer_id, multiaddr);
}
}
SwarmEvent::Behaviour(MyBehaviourEvent::Kademlia(KademliaEvent::OutboundQueryProgressed { result, ..})) => {
SwarmEvent::Behaviour(MyBehaviourEvent::Kademlia(kad::Event::OutboundQueryProgressed { result, ..})) => {
match result {
QueryResult::GetProviders(Ok(GetProvidersOk::FoundProviders { key, providers, .. })) => {
kad::QueryResult::GetProviders(Ok(kad::GetProvidersOk::FoundProviders { key, providers, .. })) => {
for peer in providers {
println!(
"Peer {peer:?} provides key {:?}",
std::str::from_utf8(key.as_ref()).unwrap()
);
}
}
QueryResult::GetProviders(Err(err)) => {
kad::QueryResult::GetProviders(Err(err)) => {
eprintln!("Failed to get providers: {err:?}");
}
QueryResult::GetRecord(Ok(
GetRecordOk::FoundRecord(PeerRecord {
record: Record { key, value, .. },
kad::QueryResult::GetRecord(Ok(
kad::GetRecordOk::FoundRecord(kad::PeerRecord {
record: kad::Record { key, value, .. },
..
})
)) => {
Expand All @@ -132,26 +129,26 @@ async fn main() -> Result<(), Box<dyn Error>> {
std::str::from_utf8(&value).unwrap(),
);
}
QueryResult::GetRecord(Ok(_)) => {}
QueryResult::GetRecord(Err(err)) => {
kad::QueryResult::GetRecord(Ok(_)) => {}
kad::QueryResult::GetRecord(Err(err)) => {
eprintln!("Failed to get record: {err:?}");
}
QueryResult::PutRecord(Ok(PutRecordOk { key })) => {
kad::QueryResult::PutRecord(Ok(kad::PutRecordOk { key })) => {
println!(
"Successfully put record {:?}",
std::str::from_utf8(key.as_ref()).unwrap()
);
}
QueryResult::PutRecord(Err(err)) => {
kad::QueryResult::PutRecord(Err(err)) => {
eprintln!("Failed to put record: {err:?}");
}
QueryResult::StartProviding(Ok(AddProviderOk { key })) => {
kad::QueryResult::StartProviding(Ok(kad::AddProviderOk { key })) => {
println!(
"Successfully put provider record {:?}",
std::str::from_utf8(key.as_ref()).unwrap()
);
}
QueryResult::StartProviding(Err(err)) => {
kad::QueryResult::StartProviding(Err(err)) => {
eprintln!("Failed to put provider record: {err:?}");
}
_ => {}
Expand All @@ -163,14 +160,14 @@ async fn main() -> Result<(), Box<dyn Error>> {
}
}

fn handle_input_line(kademlia: &mut Kademlia<MemoryStore>, line: String) {
fn handle_input_line(kademlia: &mut kad::Behaviour<MemoryStore>, line: String) {
let mut args = line.split(' ');

match args.next() {
Some("GET") => {
let key = {
match args.next() {
Some(key) => Key::new(&key),
Some(key) => kad::record::Key::new(&key),
None => {
eprintln!("Expected key");
return;
Expand All @@ -182,7 +179,7 @@ fn handle_input_line(kademlia: &mut Kademlia<MemoryStore>, line: String) {
Some("GET_PROVIDERS") => {
let key = {
match args.next() {
Some(key) => Key::new(&key),
Some(key) => kad::record::Key::new(&key),
None => {
eprintln!("Expected key");
return;
Expand All @@ -194,7 +191,7 @@ fn handle_input_line(kademlia: &mut Kademlia<MemoryStore>, line: String) {
Some("PUT") => {
let key = {
match args.next() {
Some(key) => Key::new(&key),
Some(key) => kad::record::Key::new(&key),
None => {
eprintln!("Expected key");
return;
Expand All @@ -210,20 +207,20 @@ fn handle_input_line(kademlia: &mut Kademlia<MemoryStore>, line: String) {
}
}
};
let record = Record {
let record = kad::Record {
key,
value,
publisher: None,
expires: None,
};
kademlia
.put_record(record, Quorum::One)
.put_record(record, kad::Quorum::One)
.expect("Failed to store record locally.");
}
Some("PUT_PROVIDER") => {
let key = {
match args.next() {
Some(key) => Key::new(&key),
Some(key) => kad::record::Key::new(&key),
None => {
eprintln!("Expected key");
return;
Expand Down
39 changes: 18 additions & 21 deletions examples/file-sharing/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@ use futures::prelude::*;

use libp2p::{
core::Multiaddr,
identity,
kad::{
self, record::store::MemoryStore, GetProvidersOk, Kademlia, KademliaEvent, QueryId,
QueryResult,
},
identity, kad,
multiaddr::Protocol,
noise,
request_response::{self, ProtocolSupport, RequestId, ResponseChannel},
Expand Down Expand Up @@ -56,7 +52,7 @@ pub(crate) async fn new(
let mut swarm = SwarmBuilder::with_async_std_executor(
transport,
ComposedBehaviour {
kademlia: Kademlia::new(peer_id, MemoryStore::new(peer_id)),
kademlia: kad::Behaviour::new(peer_id, kad::record::store::MemoryStore::new(peer_id)),
request_response: request_response::cbor::Behaviour::new(
[(
StreamProtocol::new("/file-exchange/1"),
Expand Down Expand Up @@ -179,8 +175,8 @@ pub(crate) struct EventLoop {
command_receiver: mpsc::Receiver<Command>,
event_sender: mpsc::Sender<Event>,
pending_dial: HashMap<PeerId, oneshot::Sender<Result<(), Box<dyn Error + Send>>>>,
pending_start_providing: HashMap<QueryId, oneshot::Sender<()>>,
pending_get_providers: HashMap<QueryId, oneshot::Sender<HashSet<PeerId>>>,
pending_start_providing: HashMap<kad::QueryId, oneshot::Sender<()>>,
pending_get_providers: HashMap<kad::QueryId, oneshot::Sender<HashSet<PeerId>>>,
pending_request_file:
HashMap<RequestId, oneshot::Sender<Result<Vec<u8>, Box<dyn Error + Send>>>>,
}
Expand Down Expand Up @@ -221,9 +217,9 @@ impl EventLoop {
) {
match event {
SwarmEvent::Behaviour(ComposedEvent::Kademlia(
KademliaEvent::OutboundQueryProgressed {
kad::Event::OutboundQueryProgressed {
id,
result: QueryResult::StartProviding(_),
result: kad::QueryResult::StartProviding(_),
..
},
)) => {
Expand All @@ -234,11 +230,12 @@ impl EventLoop {
let _ = sender.send(());
}
SwarmEvent::Behaviour(ComposedEvent::Kademlia(
KademliaEvent::OutboundQueryProgressed {
kad::Event::OutboundQueryProgressed {
id,
result:
QueryResult::GetProviders(Ok(GetProvidersOk::FoundProviders {
providers, ..
kad::QueryResult::GetProviders(Ok(kad::GetProvidersOk::FoundProviders {
providers,
..
})),
..
},
Expand All @@ -256,11 +253,11 @@ impl EventLoop {
}
}
SwarmEvent::Behaviour(ComposedEvent::Kademlia(
KademliaEvent::OutboundQueryProgressed {
kad::Event::OutboundQueryProgressed {
result:
QueryResult::GetProviders(Ok(GetProvidersOk::FinishedWithNoAdditionalRecord {
..
})),
kad::QueryResult::GetProviders(Ok(
kad::GetProvidersOk::FinishedWithNoAdditionalRecord { .. },
)),
..
},
)) => {}
Expand Down Expand Up @@ -412,13 +409,13 @@ impl EventLoop {
#[behaviour(to_swarm = "ComposedEvent")]
struct ComposedBehaviour {
request_response: request_response::cbor::Behaviour<FileRequest, FileResponse>,
kademlia: Kademlia<MemoryStore>,
kademlia: kad::Behaviour<kad::record::store::MemoryStore>,
}

#[derive(Debug)]
enum ComposedEvent {
RequestResponse(request_response::Event<FileRequest, FileResponse>),
Kademlia(KademliaEvent),
Kademlia(kad::Event),
}

impl From<request_response::Event<FileRequest, FileResponse>> for ComposedEvent {
Expand All @@ -427,8 +424,8 @@ impl From<request_response::Event<FileRequest, FileResponse>> for ComposedEvent
}
}

impl From<KademliaEvent> for ComposedEvent {
fn from(event: KademliaEvent) -> Self {
impl From<kad::Event> for ComposedEvent {
fn from(event: kad::Event) -> Self {
ComposedEvent::Kademlia(event)
}
}
Expand Down
12 changes: 6 additions & 6 deletions examples/ipfs-kad/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
#![doc = include_str!("../README.md")]

use futures::StreamExt;
use libp2p::kad;
use libp2p::kad::record::store::MemoryStore;
use libp2p::kad::{GetClosestPeersError, Kademlia, KademliaConfig, KademliaEvent, QueryResult};
use libp2p::{
development_transport, identity,
swarm::{SwarmBuilder, SwarmEvent},
Expand Down Expand Up @@ -51,10 +51,10 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Create a swarm to manage peers and events.
let mut swarm = {
// Create a Kademlia behaviour.
let mut cfg = KademliaConfig::default();
let mut cfg = kad::Config::default();
cfg.set_query_timeout(Duration::from_secs(5 * 60));
let store = MemoryStore::new(local_peer_id);
let mut behaviour = Kademlia::with_config(local_peer_id, store, cfg);
let mut behaviour = kad::Behaviour::with_config(local_peer_id, store, cfg);

// Add the bootnodes to the local routing table. `libp2p-dns` built
// into the `transport` resolves the `dnsaddr` when Kademlia tries
Expand All @@ -78,8 +78,8 @@ async fn main() -> Result<(), Box<dyn Error>> {

loop {
let event = swarm.select_next_some().await;
if let SwarmEvent::Behaviour(KademliaEvent::OutboundQueryProgressed {
result: QueryResult::GetClosestPeers(result),
if let SwarmEvent::Behaviour(kad::Event::OutboundQueryProgressed {
result: kad::QueryResult::GetClosestPeers(result),
..
}) = event
{
Expand All @@ -93,7 +93,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
println!("Query finished with no closest peers.")
}
}
Err(GetClosestPeersError::Timeout { peers, .. }) => {
Err(kad::GetClosestPeersError::Timeout { peers, .. }) => {
if !peers.is_empty() {
println!("Query timed out with closest peers: {peers:#?}")
} else {
Expand Down
10 changes: 5 additions & 5 deletions misc/metrics/src/kad.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,10 @@ impl Metrics {
}
}

impl super::Recorder<libp2p_kad::KademliaEvent> for Metrics {
fn record(&self, event: &libp2p_kad::KademliaEvent) {
impl super::Recorder<libp2p_kad::Event> for Metrics {
fn record(&self, event: &libp2p_kad::Event) {
match event {
libp2p_kad::KademliaEvent::OutboundQueryProgressed { result, stats, .. } => {
libp2p_kad::Event::OutboundQueryProgressed { result, stats, .. } => {
self.query_result_num_requests
.get_or_create(&result.into())
.observe(stats.num_requests().into());
Expand Down Expand Up @@ -217,7 +217,7 @@ impl super::Recorder<libp2p_kad::KademliaEvent> for Metrics {
_ => {}
}
}
libp2p_kad::KademliaEvent::RoutingUpdated {
libp2p_kad::Event::RoutingUpdated {
is_new_peer,
old_peer,
bucket_range: (low, _high),
Expand Down Expand Up @@ -250,7 +250,7 @@ impl super::Recorder<libp2p_kad::KademliaEvent> for Metrics {
}
}

libp2p_kad::KademliaEvent::InboundRequest { request } => {
libp2p_kad::Event::InboundRequest { request } => {
self.inbound_requests.get_or_create(&request.into()).inc();
}
_ => {}
Expand Down
4 changes: 2 additions & 2 deletions misc/metrics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ impl Recorder<libp2p_identify::Event> for Metrics {
}

#[cfg(feature = "kad")]
impl Recorder<libp2p_kad::KademliaEvent> for Metrics {
fn record(&self, event: &libp2p_kad::KademliaEvent) {
impl Recorder<libp2p_kad::Event> for Metrics {
fn record(&self, event: &libp2p_kad::Event) {
self.kad.record(event)
}
}
Expand Down
Loading

0 comments on commit c8b5f49

Please sign in to comment.