Skip to content

Commit b7f33f6

Browse files
committed
Use async-io.
1 parent c214ab5 commit b7f33f6

File tree

6 files changed

+56
-90
lines changed

6 files changed

+56
-90
lines changed

Cargo.toml

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ default = [
1717
"identify",
1818
"kad",
1919
"gossipsub",
20-
"mdns-async-std",
20+
"mdns",
2121
"mplex",
2222
"noise",
2323
"ping",
@@ -37,8 +37,7 @@ floodsub = ["libp2p-floodsub"]
3737
identify = ["libp2p-identify"]
3838
kad = ["libp2p-kad"]
3939
gossipsub = ["libp2p-gossipsub"]
40-
mdns-async-std = ["libp2p-mdns", "libp2p-mdns/async-std"]
41-
mdns-tokio = ["libp2p-mdns", "libp2p-mdns/tokio"]
40+
mdns = ["libp2p-mdns"]
4241
mplex = ["libp2p-mplex"]
4342
noise = ["libp2p-noise"]
4443
ping = ["libp2p-ping"]
@@ -125,4 +124,4 @@ members = [
125124

126125
[[example]]
127126
name = "chat-tokio"
128-
required-features = ["tcp-tokio", "mdns-tokio"]
127+
required-features = ["tcp-tokio", "mdns"]

protocols/mdns/Cargo.toml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ keywords = ["peer-to-peer", "libp2p", "networking"]
1010
categories = ["network-programming", "asynchronous"]
1111

1212
[dependencies]
13-
async-std = { version = "1.6.2", optional = true }
13+
async-io = "1.2.0"
14+
either = "1.5.3"
1415
data-encoding = "2.0"
1516
dns-parser = "0.8"
16-
either = "1.5.3"
1717
futures = "0.3.1"
1818
if-watch = "0.1.2"
1919
lazy_static = "1.2"
@@ -23,10 +23,10 @@ log = "0.4"
2323
net2 = "0.2"
2424
rand = "0.7"
2525
smallvec = "1.0"
26-
tokio = { version = "0.3", default-features = false, features = ["net"], optional = true }
2726
void = "1.0"
2827
wasm-timer = "0.2.4"
2928

3029
[dev-dependencies]
30+
async-std = "1.7.0"
3131
if-addrs = "0.6.4"
3232
tokio = { version = "0.3", default-features = false, features = ["rt", "rt-multi-thread"] }

protocols/mdns/src/behaviour.rs

Lines changed: 28 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
1919
// DEALINGS IN THE SOFTWARE.
2020

21-
use crate::service::{MdnsPacket, build_query_response, build_service_discovery_response};
21+
use crate::service::{MdnsPacket, MdnsService, build_query_response, build_service_discovery_response};
2222
use futures::prelude::*;
2323
use libp2p_core::{
2424
Multiaddr,
@@ -41,14 +41,11 @@ use wasm_timer::{Delay, Instant};
4141

4242
const MDNS_RESPONSE_TTL: std::time::Duration = Duration::from_secs(5 * 60);
4343

44-
macro_rules! codegen {
45-
($feature_name:expr, $behaviour_name:ident, $maybe_busy_wrapper:ident, $service_name:ty) => {
46-
4744
/// A `NetworkBehaviour` for mDNS. Automatically discovers peers on the local network and adds
4845
/// them to the topology.
49-
pub struct $behaviour_name {
46+
pub struct Mdns {
5047
/// The inner service.
51-
service: $maybe_busy_wrapper,
48+
service: MdnsBusyWrapper,
5249

5350
/// List of nodes that we have discovered, the address, and when their TTL expires.
5451
///
@@ -66,37 +63,37 @@ pub struct $behaviour_name {
6663
/// and a `MdnsPacket` (similar to the old Tokio socket send style). The two states are thus `Free`
6764
/// with an `MdnsService` or `Busy` with a future returning the original `MdnsService` and an
6865
/// `MdnsPacket`.
69-
enum $maybe_busy_wrapper {
70-
Free($service_name),
71-
Busy(Pin<Box<dyn Future<Output = ($service_name, MdnsPacket)> + Send>>),
66+
enum MdnsBusyWrapper {
67+
Free(MdnsService),
68+
Busy(Pin<Box<dyn Future<Output = (MdnsService, MdnsPacket)> + Send>>),
7269
Poisoned,
7370
}
7471

75-
impl fmt::Debug for $maybe_busy_wrapper {
72+
impl fmt::Debug for MdnsBusyWrapper {
7673
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
7774
match self {
78-
$maybe_busy_wrapper::Free(service) => {
79-
fmt.debug_struct("$maybe_busy_wrapper::Free")
75+
Self::Free(service) => {
76+
fmt.debug_struct("MdnsBusyWrapper::Free")
8077
.field("service", service)
8178
.finish()
8279
},
83-
$maybe_busy_wrapper::Busy(_) => {
84-
fmt.debug_struct("$maybe_busy_wrapper::Busy")
80+
Self::Busy(_) => {
81+
fmt.debug_struct("MdnsBusyWrapper::Busy")
8582
.finish()
8683
}
87-
$maybe_busy_wrapper::Poisoned => {
88-
fmt.debug_struct("$maybe_busy_wrapper::Poisoned")
84+
Self::Poisoned => {
85+
fmt.debug_struct("MdnsBusyWrapper::Poisoned")
8986
.finish()
9087
}
9188
}
9289
}
9390
}
9491

95-
impl $behaviour_name {
92+
impl Mdns {
9693
/// Builds a new `Mdns` behaviour.
97-
pub async fn new() -> io::Result<$behaviour_name> {
98-
Ok($behaviour_name {
99-
service: $maybe_busy_wrapper::Free(<$service_name>::new().await?),
94+
pub async fn new() -> io::Result<Self> {
95+
Ok(Self {
96+
service: MdnsBusyWrapper::Free(MdnsService::new().await?),
10097
discovered_nodes: SmallVec::new(),
10198
closest_expiration: None,
10299
})
@@ -113,7 +110,7 @@ impl $behaviour_name {
113110
}
114111
}
115112

116-
impl NetworkBehaviour for $behaviour_name {
113+
impl NetworkBehaviour for Mdns {
117114
type ProtocolsHandler = DummyProtocolsHandler;
118115
type OutEvent = MdnsEvent;
119116

@@ -179,32 +176,32 @@ impl NetworkBehaviour for $behaviour_name {
179176

180177
// Polling the mDNS service, and obtain the list of nodes discovered this round.
181178
let discovered = loop {
182-
let service = mem::replace(&mut self.service, $maybe_busy_wrapper::Poisoned);
179+
let service = mem::replace(&mut self.service, MdnsBusyWrapper::Poisoned);
183180

184181
let packet = match service {
185-
$maybe_busy_wrapper::Free(service) => {
186-
self.service = $maybe_busy_wrapper::Busy(Box::pin(service.next()));
182+
MdnsBusyWrapper::Free(service) => {
183+
self.service = MdnsBusyWrapper::Busy(Box::pin(service.next()));
187184
continue;
188185
},
189-
$maybe_busy_wrapper::Busy(mut fut) => {
186+
MdnsBusyWrapper::Busy(mut fut) => {
190187
match fut.as_mut().poll(cx) {
191188
Poll::Ready((service, packet)) => {
192-
self.service = $maybe_busy_wrapper::Free(service);
189+
self.service = MdnsBusyWrapper::Free(service);
193190
packet
194191
},
195192
Poll::Pending => {
196-
self.service = $maybe_busy_wrapper::Busy(fut);
193+
self.service = MdnsBusyWrapper::Busy(fut);
197194
return Poll::Pending;
198195
}
199196
}
200197
},
201-
$maybe_busy_wrapper::Poisoned => panic!("Mdns poisoned"),
198+
MdnsBusyWrapper::Poisoned => panic!("Mdns poisoned"),
202199
};
203200

204201
match packet {
205202
MdnsPacket::Query(query) => {
206203
// MaybeBusyMdnsService should always be Free.
207-
if let $maybe_busy_wrapper::Free(ref mut service) = self.service {
204+
if let MdnsBusyWrapper::Free(ref mut service) = self.service {
208205
let resp = build_query_response(
209206
query.query_id(),
210207
params.local_peer_id().clone(),
@@ -256,7 +253,7 @@ impl NetworkBehaviour for $behaviour_name {
256253
},
257254
MdnsPacket::ServiceDiscovery(disc) => {
258255
// MaybeBusyMdnsService should always be Free.
259-
if let $maybe_busy_wrapper::Free(ref mut service) = self.service {
256+
if let MdnsBusyWrapper::Free(ref mut service) = self.service {
260257
let resp = build_service_discovery_response(
261258
disc.query_id(),
262259
MDNS_RESPONSE_TTL,
@@ -281,23 +278,14 @@ impl NetworkBehaviour for $behaviour_name {
281278
}
282279
}
283280

284-
impl fmt::Debug for $behaviour_name {
281+
impl fmt::Debug for Mdns {
285282
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
286283
fmt.debug_struct("Mdns")
287284
.field("service", &self.service)
288285
.finish()
289286
}
290287
}
291288

292-
};
293-
}
294-
295-
#[cfg(feature = "async-std")]
296-
codegen!("async-std", Mdns, MaybeBusyMdnsService, crate::service::MdnsService);
297-
298-
#[cfg(feature = "tokio")]
299-
codegen!("tokio", TokioMdns, MaybeBusyTokioMdnsService, crate::service::TokioMdnsService);
300-
301289
/// Event that can be produced by the `Mdns` behaviour.
302290
#[derive(Debug)]
303291
pub enum MdnsEvent {

protocols/mdns/src/lib.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,10 @@ const SERVICE_NAME: &[u8] = b"_p2p._udp.local";
3535
/// Hardcoded name of the service used for DNS-SD.
3636
const META_QUERY_SERVICE: &[u8] = b"_services._dns-sd._udp.local";
3737

38-
#[cfg(feature = "async-std")]
39-
pub use self::{behaviour::Mdns, service::MdnsService};
40-
#[cfg(feature = "tokio")]
41-
pub use self::{behaviour::TokioMdns, service::TokioMdnsService};
42-
43-
pub use self::behaviour::MdnsEvent;
38+
pub use crate::{
39+
behaviour::{Mdns, MdnsEvent},
40+
service::MdnsService,
41+
};
4442

4543
mod behaviour;
4644
mod dns;

protocols/mdns/src/service.rs

Lines changed: 16 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,13 @@
1919
// DEALINGS IN THE SOFTWARE.
2020

2121
use crate::{SERVICE_NAME, META_QUERY_SERVICE, dns};
22+
use async_io::Async;
2223
use dns_parser::{Packet, RData};
2324
use either::Either::{Left, Right};
2425
use futures::{future, prelude::*};
2526
use libp2p_core::{multiaddr::{Multiaddr, Protocol}, PeerId};
2627
use log::warn;
27-
use std::{convert::TryFrom as _, fmt, io, net::Ipv4Addr, net::SocketAddr, str, time::{Duration, Instant}};
28+
use std::{convert::TryFrom, fmt, io, net::Ipv4Addr, net::{UdpSocket, SocketAddr}, str, time::{Duration, Instant}};
2829
use wasm_timer::Interval;
2930
use lazy_static::lazy_static;
3031

@@ -37,9 +38,6 @@ lazy_static! {
3738
));
3839
}
3940

40-
macro_rules! codegen {
41-
($feature_name:expr, $service_name:ident, $udp_socket:ty, $udp_socket_from_std:tt) => {
42-
4341
/// A running service that discovers libp2p peers and responds to other libp2p peers' queries on
4442
/// the local network.
4543
///
@@ -71,10 +69,7 @@ macro_rules! codegen {
7169
/// # let my_peer_id = PeerId::from(identity::Keypair::generate_ed25519().public());
7270
/// # let my_listened_addrs: Vec<Multiaddr> = vec![];
7371
/// # async {
74-
/// # #[cfg(feature = "async-std")]
7572
/// # let mut service = libp2p_mdns::service::MdnsService::new().await.unwrap();
76-
/// # #[cfg(feature = "tokio")]
77-
/// # let mut service = libp2p_mdns::service::TokioMdnsService::new().await.unwrap();
7873
/// let _future_to_poll = async {
7974
/// let (mut service, packet) = service.next().await;
8075
///
@@ -108,13 +103,12 @@ macro_rules! codegen {
108103
/// };
109104
/// # };
110105
/// # }
111-
#[cfg_attr(docsrs, doc(cfg(feature = $feature_name)))]
112-
pub struct $service_name {
106+
pub struct MdnsService {
113107
/// Main socket for listening.
114-
socket: $udp_socket,
108+
socket: Async<UdpSocket>,
115109

116110
/// Socket for sending queries on the network.
117-
query_socket: $udp_socket,
111+
query_socket: Async<UdpSocket>,
118112

119113
/// Interval for sending queries.
120114
query_interval: Interval,
@@ -137,42 +131,41 @@ pub struct $service_name {
137131
if_watch: if_watch::IfWatcher,
138132
}
139133

140-
impl $service_name {
134+
impl MdnsService {
141135
/// Starts a new mDNS service.
142-
pub async fn new() -> io::Result<$service_name> {
136+
pub async fn new() -> io::Result<Self> {
143137
Self::new_inner(false).await
144138
}
145139

146140
/// Same as `new`, but we don't automatically send queries on the network.
147-
pub async fn silent() -> io::Result<$service_name> {
141+
pub async fn silent() -> io::Result<Self> {
148142
Self::new_inner(true).await
149143
}
150144

151145
/// Starts a new mDNS service.
152-
async fn new_inner(silent: bool) -> io::Result<$service_name> {
146+
async fn new_inner(silent: bool) -> io::Result<Self> {
153147
let socket = {
154148
let builder = net2::UdpBuilder::new_v4()?;
155149
builder.reuse_address(true)?;
156150
#[cfg(unix)]
157151
net2::unix::UnixUdpBuilderExt::reuse_port(&builder, true)?;
158152
let socket = builder.bind((Ipv4Addr::UNSPECIFIED, 5353))?;
159-
let socket = $udp_socket_from_std(socket)?;
160153
socket.set_multicast_loop_v4(true)?;
161154
socket.set_multicast_ttl_v4(255)?;
162-
socket
155+
Async::new(socket)?
163156
};
164157

165158
// Given that we pass an IP address to bind, which does not need to be resolved, we can
166159
// use std::net::UdpSocket::bind, instead of its async counterpart from async-std.
167160
let query_socket = {
168161
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))?;
169-
$udp_socket_from_std(socket)?
162+
Async::new(socket)?
170163
};
171164

172165

173166
let if_watch = if_watch::IfWatcher::new().await?;
174167

175-
Ok($service_name {
168+
Ok(Self {
176169
socket,
177170
query_socket,
178171
query_interval: Interval::new_at(Instant::now(), Duration::from_secs(20)),
@@ -217,7 +210,8 @@ impl $service_name {
217210
if let Ok(if_watch::IfEvent::Up(inet)) = event {
218211
if inet.addr().is_ipv4() && !inet.addr().is_loopback() {
219212
self.socket
220-
.join_multicast_v4(From::from([224, 0, 0, 251]), Ipv4Addr::UNSPECIFIED)
213+
.get_ref()
214+
.join_multicast_v4(&From::from([224, 0, 0, 251]), &Ipv4Addr::UNSPECIFIED)
221215
.ok();
222216
}
223217
}
@@ -294,25 +288,14 @@ impl $service_name {
294288
}
295289
}
296290

297-
impl fmt::Debug for $service_name {
291+
impl fmt::Debug for MdnsService {
298292
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
299293
fmt.debug_struct("$service_name")
300294
.field("silent", &self.silent)
301295
.finish()
302296
}
303297
}
304298

305-
};
306-
}
307-
308-
#[cfg(feature = "async-std")]
309-
codegen!("async-std", MdnsService, async_std::net::UdpSocket, (|socket| Ok::<_, std::io::Error>(async_std::net::UdpSocket::from(socket))));
310-
311-
// Note: Tokio's UdpSocket::from_std does not set the socket into non-blocking mode.
312-
#[cfg(feature = "tokio")]
313-
codegen!("tokio", TokioMdnsService, tokio::net::UdpSocket, (|socket: std::net::UdpSocket| { socket.set_nonblocking(true); tokio::net::UdpSocket::from_std(socket) }));
314-
315-
316299
/// A valid mDNS packet received by the service.
317300
#[derive(Debug)]
318301
pub enum MdnsPacket {
@@ -700,17 +683,15 @@ mod tests {
700683
}
701684
}
702685

703-
#[cfg(feature = "async-std")]
704686
testgen!(
705687
async_std,
706688
crate::service::MdnsService,
707689
(|fut| async_std::task::block_on::<_, ()>(fut))
708690
);
709691

710-
#[cfg(feature = "tokio")]
711692
testgen!(
712693
tokio,
713-
crate::service::TokioMdnsService,
694+
crate::service::MdnsService,
714695
(|fut| tokio::runtime::Runtime::new().unwrap().block_on::<futures::future::BoxFuture<()>>(fut))
715696
);
716697
}

src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,8 @@ pub use libp2p_gossipsub as gossipsub;
196196
#[cfg_attr(docsrs, doc(cfg(feature = "mplex")))]
197197
#[doc(inline)]
198198
pub use libp2p_mplex as mplex;
199-
#[cfg(any(feature = "mdns-async-std", feature = "mdns-tokio"))]
200-
#[cfg_attr(docsrs, doc(cfg(any(feature = "mdns-async-std", feature = "mdns-tokio"))))]
199+
#[cfg(feature = "mdns")]
200+
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
201201
#[cfg(not(any(target_os = "emscripten", target_os = "wasi", target_os = "unknown")))]
202202
#[doc(inline)]
203203
pub use libp2p_mdns as mdns;

0 commit comments

Comments
 (0)