Skip to content

Commit

Permalink
Merge pull request #20 from algesten/anyhow
Browse files Browse the repository at this point in the history
Refactor out use of anyhow
  • Loading branch information
Rusty Rain committed Oct 8, 2021
2 parents 5a04493 + c56861d commit 634553b
Show file tree
Hide file tree
Showing 22 changed files with 144 additions and 140 deletions.
5 changes: 2 additions & 3 deletions crates/mdns/Cargo.toml
Expand Up @@ -16,12 +16,11 @@ default = [ "reuse_port" ]
reuse_port = []

[dependencies]
util = { package = "webrtc-util", version = "0.4.3", default-features = false, features = ["ifaces"] }
util = { package = "webrtc-util", version = "0.5.0", default-features = false, features = ["ifaces"] }
tokio = { version = "1.12.0", features = ["full"] }
socket2 = { version = "0.4.2", features = ["all"] }
log = "0.4"
thiserror = "1.0.29"
anyhow = "1.0.44"
thiserror = "1.0"

[dev-dependencies]
env_logger = "0.9"
Expand Down
4 changes: 2 additions & 2 deletions crates/mdns/examples/mdns_query.rs
@@ -1,8 +1,8 @@
use webrtc_mdns as mdns;

use mdns::Error;
use mdns::{config::*, conn::*};

use anyhow::Result;
use clap::{App, AppSettings, Arg};
use std::net::SocketAddr;
use std::str::FromStr;
Expand All @@ -15,7 +15,7 @@ use tokio::sync::mpsc;
// cargo run --color=always --package webrtc-mdns --example mdns_query -- --local-name pion-test.local

#[tokio::main]
async fn main() -> Result<()> {
async fn main() -> Result<(), Error> {
env_logger::init();

let mut app = App::new("mDNS Query")
Expand Down
4 changes: 2 additions & 2 deletions crates/mdns/examples/mdns_server.rs
@@ -1,8 +1,8 @@
use webrtc_mdns as mdns;

use mdns::Error;
use mdns::{config::*, conn::*};

use anyhow::Result;
use clap::{App, AppSettings, Arg};
use std::net::SocketAddr;
use std::str::FromStr;
Expand All @@ -14,7 +14,7 @@ use std::str::FromStr;
// cargo run --color=always --package webrtc-mdns --example mdns_server -- --local-name pion-test.local

#[tokio::main]
async fn main() -> Result<()> {
async fn main() -> Result<(), Error> {
env_logger::init();

let mut app = App::new("mDNS Sever")
Expand Down
2 changes: 1 addition & 1 deletion crates/mdns/src/conn/conn_test.rs
Expand Up @@ -13,7 +13,7 @@ mod test {
server_a.close().await?;

if let Err(err) = server_a.close().await {
assert!(Error::ErrConnectionClosed.equal(&err));
assert_eq!(Error::ErrConnectionClosed, err);
} else {
assert!(false, "expected error, but got ok");
}
Expand Down
19 changes: 9 additions & 10 deletions crates/mdns/src/conn/mod.rs
Expand Up @@ -7,7 +7,6 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;

use anyhow::Result;
use core::sync::atomic;
use socket2::SockAddr;
use tokio::net::{ToSocketAddrs, UdpSocket};
Expand Down Expand Up @@ -71,7 +70,7 @@ impl DnsConn {
Ok(e) => e,
Err(e) => {
log::error!("Error getting interfaces: {:?}", e);
return Err(Error::new(e.to_string()).into());
return Err(Error::Other(e.to_string()));
}
};

Expand All @@ -89,7 +88,7 @@ impl DnsConn {
}

if join_error_count >= interfaces.len() {
return Err(Error::ErrJoiningMulticastGroup.into());
return Err(Error::ErrJoiningMulticastGroup);
}
}

Expand Down Expand Up @@ -143,7 +142,7 @@ impl DnsConn {
pub async fn close(&self) -> Result<()> {
log::info!("Closing connection");
if self.is_server_closed.load(atomic::Ordering::SeqCst) {
return Err(Error::ErrConnectionClosed.into());
return Err(Error::ErrConnectionClosed);
}

log::trace!("Sending close command to server");
Expand All @@ -154,7 +153,7 @@ impl DnsConn {
}
Err(e) => {
log::warn!("Error sending close command to server: {:?}", e);
Err(Error::ErrConnectionClosed.into())
Err(Error::ErrConnectionClosed)
}
}
}
Expand All @@ -167,7 +166,7 @@ impl DnsConn {
mut close_query_signal: mpsc::Receiver<()>,
) -> Result<(ResourceHeader, SocketAddr)> {
if self.is_server_closed.load(atomic::Ordering::SeqCst) {
return Err(Error::ErrConnectionClosed.into());
return Err(Error::ErrConnectionClosed);
}

let name_with_suffix = name.to_owned() + ".";
Expand All @@ -193,7 +192,7 @@ impl DnsConn {

_ = close_query_signal.recv() => {
log::info!("Query close signal received.");
return Err(Error::ErrConnectionClosed.into())
return Err(Error::ErrConnectionClosed)
},

res_opt = query_rx.recv() =>{
Expand Down Expand Up @@ -321,7 +320,7 @@ async fn run(
let q = match p.question() {
Ok(q) => q,
Err(err) => {
if Error::ErrSectionDone.equal(&err) {
if Error::ErrSectionDone == err {
log::trace!("Parsing has completed");
break;
} else {
Expand Down Expand Up @@ -353,7 +352,7 @@ async fn run(
let a = match p.answer_header() {
Ok(a) => a,
Err(err) => {
if !Error::ErrSectionDone.equal(&err) {
if Error::ErrSectionDone != err {
log::warn!("Failed to parse mDNS packet {}", err);
}
return;
Expand Down Expand Up @@ -407,7 +406,7 @@ async fn send_answer(
a: match interface_addr.ip() {
IpAddr::V4(ip) => ip.octets(),
IpAddr::V6(_) => {
return Err(Error::new("Unexpected IpV6 addr".to_owned()).into())
return Err(Error::Other("Unexpected IpV6 addr".to_owned()))
}
},
})),
Expand Down
34 changes: 28 additions & 6 deletions crates/mdns/src/error.rs
@@ -1,6 +1,13 @@
use thiserror::Error;

use std::io;
use std::net;
use std::string::FromUtf8Error;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum Error {
#[error("mDNS: failed to join multicast group")]
ErrJoiningMulticastGroup,
Expand Down Expand Up @@ -52,14 +59,29 @@ pub enum Error {
ErrCompressedSrv,
#[error("empty builder msg")]
ErrEmptyBuilderMsg,

#[allow(non_camel_case_types)]
#[error("{0}")]
new(String),
Io(#[source] IoError),
#[error("utf-8 error: {0}")]
Utf8(#[from] FromUtf8Error),
#[error("parse addr: {0}")]
ParseIp(#[from] net::AddrParseError),
#[error("{0}")]
Other(String),
}

#[derive(Debug, Error)]
#[error("io error: {0}")]
pub struct IoError(#[from] pub io::Error);

// Workaround for wanting PartialEq for io::Error.
impl PartialEq for IoError {
fn eq(&self, other: &Self) -> bool {
self.0.kind() == other.0.kind()
}
}

impl Error {
pub fn equal(&self, err: &anyhow::Error) -> bool {
err.downcast_ref::<Self>().map_or(false, |e| e == self)
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Error::Io(IoError(e))
}
}
4 changes: 3 additions & 1 deletion crates/mdns/src/lib.rs
Expand Up @@ -3,5 +3,7 @@

pub mod config;
pub mod conn;
pub mod error;
mod error;
pub mod message;

pub use error::Error;
27 changes: 13 additions & 14 deletions crates/mdns/src/message/builder.rs
Expand Up @@ -4,7 +4,6 @@ use super::resource::*;
use super::*;
use crate::error::*;

use anyhow::Result;
use std::collections::HashMap;

// A Builder allows incrementally packing a DNS message.
Expand Down Expand Up @@ -84,10 +83,10 @@ impl Builder {

fn start_check(&self, section: Section) -> Result<()> {
if self.section <= Section::NotStarted {
return Err(Error::ErrNotStarted.into());
return Err(Error::ErrNotStarted);
}
if self.section > section {
return Err(Error::ErrSectionDone.into());
return Err(Error::ErrSectionDone);
}

Ok(())
Expand Down Expand Up @@ -128,13 +127,13 @@ impl Builder {
Section::Answers => (&mut self.header.answers, Error::ErrTooManyAnswers),
Section::Authorities => (&mut self.header.authorities, Error::ErrTooManyAuthorities),
Section::Additionals => (&mut self.header.additionals, Error::ErrTooManyAdditionals),
Section::NotStarted => return Err(Error::ErrNotStarted.into()),
Section::Done => return Err(Error::ErrSectionDone.into()),
Section::Header => return Err(Error::ErrSectionHeader.into()),
Section::NotStarted => return Err(Error::ErrNotStarted),
Section::Done => return Err(Error::ErrSectionDone),
Section::Header => return Err(Error::ErrSectionHeader),
};

if *count == u16::MAX {
Err(err.into())
Err(err)
} else {
*count += 1;
Ok(())
Expand All @@ -144,10 +143,10 @@ impl Builder {
// question adds a single question.
pub fn add_question(&mut self, q: &Question) -> Result<()> {
if self.section < Section::Questions {
return Err(Error::ErrNotStarted.into());
return Err(Error::ErrNotStarted);
}
if self.section > Section::Questions {
return Err(Error::ErrSectionDone.into());
return Err(Error::ErrSectionDone);
}
let msg = self.msg.take();
if let Some(mut msg) = msg {
Expand All @@ -161,10 +160,10 @@ impl Builder {

fn check_resource_section(&self) -> Result<()> {
if self.section < Section::Answers {
return Err(Error::ErrNotStarted.into());
return Err(Error::ErrNotStarted);
}
if self.section > Section::Additionals {
return Err(Error::ErrSectionDone.into());
return Err(Error::ErrSectionDone);
}
Ok(())
}
Expand All @@ -176,7 +175,7 @@ impl Builder {
if let Some(body) = &r.body {
r.header.typ = body.real_type();
} else {
return Err(Error::ErrNilResourceBody.into());
return Err(Error::ErrNilResourceBody);
}

if let Some(msg) = self.msg.take() {
Expand All @@ -196,7 +195,7 @@ impl Builder {
// Finish ends message building and generates a binary message.
pub fn finish(&mut self) -> Result<Vec<u8>> {
if self.section < Section::Header {
return Err(Error::ErrNotStarted.into());
return Err(Error::ErrNotStarted);
}
self.section = Section::Done;

Expand All @@ -207,7 +206,7 @@ impl Builder {
msg[..HEADER_LEN].copy_from_slice(&buf[..HEADER_LEN]);
Ok(msg)
} else {
Err(Error::ErrEmptyBuilderMsg.into())
Err(Error::ErrEmptyBuilderMsg)
}
}
}

0 comments on commit 634553b

Please sign in to comment.