This commit is contained in:
John Smith 2021-11-27 12:44:21 -05:00
parent d1f728954c
commit 028e02f942
31 changed files with 190 additions and 207 deletions

View File

@ -161,22 +161,11 @@ impl AttachmentManager {
pub fn is_attached(&self) -> bool { pub fn is_attached(&self) -> bool {
let s = self.inner.lock().attachment_machine.state(); let s = self.inner.lock().attachment_machine.state();
match s { !matches!(s, AttachmentState::Detached | AttachmentState::Detaching)
AttachmentState::Attaching => true,
AttachmentState::AttachedWeak => true,
AttachmentState::AttachedGood => true,
AttachmentState::AttachedStrong => true,
AttachmentState::FullyAttached => true,
AttachmentState::OverAttached => true,
_ => false,
}
} }
pub fn is_detached(&self) -> bool { pub fn is_detached(&self) -> bool {
let s = self.inner.lock().attachment_machine.state(); let s = self.inner.lock().attachment_machine.state();
match s { matches!(s, AttachmentState::Detached)
AttachmentState::Detached => true,
_ => false,
}
} }
pub fn get_attach_timestamp(&self) -> Option<u64> { pub fn get_attach_timestamp(&self) -> Option<u64> {

View File

@ -89,7 +89,7 @@ where
pub async fn consume(&self, input: &T::Input) -> Result<Option<T::Output>, ()> { pub async fn consume(&self, input: &T::Input) -> Result<Option<T::Output>, ()> {
let current_state = self.inner.lock().state; let current_state = self.inner.lock().state;
if let Some(new_state) = T::transition(&current_state, &input) { if let Some(new_state) = T::transition(&current_state, input) {
let output = T::output(&current_state, input); let output = T::output(&current_state, input);
let old_state = current_state; let old_state = current_state;
let (callback, eventual) = { let (callback, eventual) = {

View File

@ -25,7 +25,7 @@ impl PartialEq for ConnectionTableEntry {
if self.last_message_recv_time != other.last_message_recv_time { if self.last_message_recv_time != other.last_message_recv_time {
return false; return false;
} }
return true; true
} }
} }
@ -46,6 +46,11 @@ impl core::fmt::Debug for ConnectionTable {
} }
} }
impl Default for ConnectionTable {
fn default() -> Self {
Self::new()
}
}
impl ConnectionTable { impl ConnectionTable {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
@ -74,7 +79,7 @@ impl ConnectionTable {
let timestamp = get_timestamp(); let timestamp = get_timestamp();
let entry = ConnectionTableEntry { let entry = ConnectionTableEntry {
conn: conn, conn,
established_time: timestamp, established_time: timestamp,
last_message_sent_time: None, last_message_sent_time: None,
last_message_recv_time: None, last_message_recv_time: None,
@ -90,10 +95,7 @@ impl ConnectionTable {
descriptor: &ConnectionDescriptor, descriptor: &ConnectionDescriptor,
) -> Option<ConnectionTableEntry> { ) -> Option<ConnectionTableEntry> {
let inner = self.inner.lock(); let inner = self.inner.lock();
match inner.conn_by_addr.get(&descriptor) { inner.conn_by_addr.get(descriptor).cloned()
Some(v) => Some(v.clone()),
None => None,
}
} }
pub fn connection_count(&self) -> usize { pub fn connection_count(&self) -> usize {
@ -107,7 +109,7 @@ impl ConnectionTable {
) -> Result<ConnectionTableEntry, ()> { ) -> Result<ConnectionTableEntry, ()> {
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
let res = inner.conn_by_addr.remove(&descriptor); let res = inner.conn_by_addr.remove(descriptor);
match res { match res {
Some(v) => Ok(v.clone()), Some(v) => Ok(v.clone()),
None => Err(()), None => Err(()),

View File

@ -871,7 +871,7 @@ impl Network {
trace!("WS: starting listener at {:?}", listen_address); trace!("WS: starting listener at {:?}", listen_address);
let (fqdn, port) = split_port(&listen_address) let (fqdn, port) = split_port(&listen_address)
.map_err(|_| "invalid WS listen address, port not specified correctly".to_owned())?; .map_err(|_| "invalid WS listen address, port not specified correctly".to_owned())?;
let port = port.ok_or_else(|| "port must be specified for WS address".to_owned())?;
let _ = self let _ = self
.start_tcp_listener( .start_tcp_listener(
listen_address.clone(), listen_address.clone(),
@ -892,6 +892,8 @@ impl Network {
let (public_fqdn, public_port) = split_port(public_address).map_err(|_| { let (public_fqdn, public_port) = split_port(public_address).map_err(|_| {
"invalid WS public address, port not specified correctly".to_owned() "invalid WS public address, port not specified correctly".to_owned()
})?; })?;
let public_port = public_port
.ok_or_else(|| "port must be specified for public WS address".to_owned())?;
routing_table.register_public_dial_info( routing_table.register_public_dial_info(
DialInfo::ws(fqdn, public_port, public_fqdn), DialInfo::ws(fqdn, public_port, public_fqdn),
@ -923,6 +925,7 @@ impl Network {
trace!("WSS: starting listener at {}", listen_address); trace!("WSS: starting listener at {}", listen_address);
let (fqdn, port) = split_port(&listen_address) let (fqdn, port) = split_port(&listen_address)
.map_err(|_| "invalid WSS listen address, port not specified correctly".to_owned())?; .map_err(|_| "invalid WSS listen address, port not specified correctly".to_owned())?;
let port = port.ok_or_else(|| "port must be specified for WSS address".to_owned())?;
let _ = self let _ = self
.start_tcp_listener( .start_tcp_listener(
@ -944,6 +947,8 @@ impl Network {
let (public_fqdn, public_port) = split_port(public_address).map_err(|_| { let (public_fqdn, public_port) = split_port(public_address).map_err(|_| {
"invalid WSS public address, port not specified correctly".to_owned() "invalid WSS public address, port not specified correctly".to_owned()
})?; })?;
let public_port = public_port
.ok_or_else(|| "port must be specified for public WSS address".to_owned())?;
routing_table.register_public_dial_info( routing_table.register_public_dial_info(
DialInfo::wss(fqdn, public_port, public_fqdn), DialInfo::wss(fqdn, public_port, public_fqdn),

View File

@ -35,7 +35,7 @@ pub struct LeaseManager {
impl LeaseManager { impl LeaseManager {
fn new_inner(network_manager: NetworkManager) -> LeaseManagerInner { fn new_inner(network_manager: NetworkManager) -> LeaseManagerInner {
LeaseManagerInner { LeaseManagerInner {
network_manager: network_manager, network_manager,
max_server_signal_leases: 1, max_server_signal_leases: 1,
max_server_relay_leases: 1, max_server_relay_leases: 1,
max_client_signal_leases: 1, max_client_signal_leases: 1,
@ -111,7 +111,7 @@ impl LeaseManager {
return false; return false;
} }
let network_class = inner.network_manager.get_network_class(); let network_class = inner.network_manager.get_network_class();
let out = match network_class { match network_class {
NetworkClass::Server => true, NetworkClass::Server => true,
NetworkClass::Mapped => true, NetworkClass::Mapped => true,
NetworkClass::FullNAT => true, NetworkClass::FullNAT => true,
@ -121,8 +121,7 @@ impl LeaseManager {
NetworkClass::WebApp => false, NetworkClass::WebApp => false,
NetworkClass::TorWebApp => false, NetworkClass::TorWebApp => false,
NetworkClass::Invalid => false, NetworkClass::Invalid => false,
}; }
return out;
} }
pub fn server_will_provide_signal_lease(&self) -> bool { pub fn server_will_provide_signal_lease(&self) -> bool {
if !self.server_can_provide_signal_lease() { if !self.server_can_provide_signal_lease() {
@ -140,7 +139,7 @@ impl LeaseManager {
return false; return false;
} }
return true; true
} }
// Relay leases // Relay leases
@ -154,7 +153,7 @@ impl LeaseManager {
return false; return false;
} }
let network_class = inner.network_manager.get_network_class(); let network_class = inner.network_manager.get_network_class();
let out = match network_class { match network_class {
NetworkClass::Server => true, NetworkClass::Server => true,
NetworkClass::Mapped => true, NetworkClass::Mapped => true,
NetworkClass::FullNAT => true, NetworkClass::FullNAT => true,
@ -164,9 +163,8 @@ impl LeaseManager {
NetworkClass::WebApp => false, NetworkClass::WebApp => false,
NetworkClass::TorWebApp => false, NetworkClass::TorWebApp => false,
NetworkClass::Invalid => false, NetworkClass::Invalid => false,
}; }
// xxx: also depends on network strength / bandwidth availability? // xxx: also depends on network strength / bandwidth availability?
return out;
} }
pub fn server_will_provide_relay_lease(&self) -> bool { pub fn server_will_provide_relay_lease(&self) -> bool {
if !self.server_can_provide_relay_lease() { if !self.server_can_provide_relay_lease() {
@ -183,6 +181,6 @@ impl LeaseManager {
if !routing_table.has_public_dial_info() { if !routing_table.has_public_dial_info() {
return false; return false;
} }
return true; true
} }
} }

View File

@ -414,7 +414,7 @@ impl NetworkManager {
// Record the receipt for later // Record the receipt for later
let exp_ts = intf::get_timestamp() + expiration_us; let exp_ts = intf::get_timestamp() + expiration_us;
let eventual = SingleShotEventual::new(ReceiptEvent::CANCELLED); let eventual = SingleShotEventual::new(ReceiptEvent::Cancelled);
let instance = eventual.instance(); let instance = eventual.instance();
receipt_manager.record_single_shot_receipt(receipt, exp_ts, eventual); receipt_manager.record_single_shot_receipt(receipt, exp_ts, eventual);
@ -462,6 +462,7 @@ impl NetworkManager {
// and if so, get the max version we can use // and if so, get the max version we can use
let version = if let Some((node_min, node_max)) = node_ref.operate(|e| e.min_max_version()) let version = if let Some((node_min, node_max)) = node_ref.operate(|e| e.min_max_version())
{ {
#[allow(clippy::absurd_extreme_comparisons)]
if node_min > MAX_VERSION || node_max < MIN_VERSION { if node_min > MAX_VERSION || node_max < MIN_VERSION {
return Err(format!( return Err(format!(
"can't talk to this node {} because version is unsupported: ({},{})", "can't talk to this node {} because version is unsupported: ({},{})",

View File

@ -7,9 +7,9 @@ use xx::*;
#[derive(Clone, Debug, Copy, PartialEq, Eq)] #[derive(Clone, Debug, Copy, PartialEq, Eq)]
pub enum ReceiptEvent { pub enum ReceiptEvent {
RETURNED, Returned,
EXPIRED, Expired,
CANCELLED, Cancelled,
} }
cfg_if! { cfg_if! {
@ -114,9 +114,9 @@ impl ReceiptRecord {
receipt_callback: impl ReceiptCallback, receipt_callback: impl ReceiptCallback,
) -> Self { ) -> Self {
Self { Self {
expiration_ts: expiration_ts, expiration_ts,
nonce: receipt.get_nonce(), nonce: receipt.get_nonce(),
expected_returns: expected_returns, expected_returns,
returns_so_far: 0u32, returns_so_far: 0u32,
receipt_callback: ReceiptRecordCallbackType::Normal(Box::new(receipt_callback)), receipt_callback: ReceiptRecordCallbackType::Normal(Box::new(receipt_callback)),
} }
@ -128,7 +128,7 @@ impl ReceiptRecord {
eventual: ReceiptSingleShotType, eventual: ReceiptSingleShotType,
) -> Self { ) -> Self {
Self { Self {
expiration_ts: expiration_ts, expiration_ts,
nonce: receipt.get_nonce(), nonce: receipt.get_nonce(),
returns_so_far: 0u32, returns_so_far: 0u32,
expected_returns: 1u32, expected_returns: 1u32,
@ -179,7 +179,7 @@ pub struct ReceiptManager {
impl ReceiptManager { impl ReceiptManager {
fn new_inner(network_manager: NetworkManager) -> ReceiptManagerInner { fn new_inner(network_manager: NetworkManager) -> ReceiptManagerInner {
ReceiptManagerInner { ReceiptManagerInner {
network_manager: network_manager, network_manager,
receipts_by_nonce: BTreeMap::new(), receipts_by_nonce: BTreeMap::new(),
next_oldest_ts: None, next_oldest_ts: None,
timeout_task: SingleFuture::new(), timeout_task: SingleFuture::new(),
@ -246,7 +246,7 @@ impl ReceiptManager {
let receipt_inner = v.lock(); let receipt_inner = v.lock();
if receipt_inner.expiration_ts <= now { if receipt_inner.expiration_ts <= now {
// Expire this receipt // Expire this receipt
expired_nonces.push(k.clone()); expired_nonces.push(*k);
} else if new_next_oldest_ts.is_none() } else if new_next_oldest_ts.is_none()
|| receipt_inner.expiration_ts < new_next_oldest_ts.unwrap() || receipt_inner.expiration_ts < new_next_oldest_ts.unwrap()
{ {
@ -254,7 +254,7 @@ impl ReceiptManager {
new_next_oldest_ts = Some(receipt_inner.expiration_ts); new_next_oldest_ts = Some(receipt_inner.expiration_ts);
} }
} }
if expired_nonces.len() == 0 { if expired_nonces.is_empty() {
return; return;
} }
// Now remove the expired receipts // Now remove the expired receipts
@ -272,7 +272,7 @@ impl ReceiptManager {
for expired_record in expired_records { for expired_record in expired_records {
let mut expired_record_mut = expired_record.lock(); let mut expired_record_mut = expired_record.lock();
if let Some(callback) = if let Some(callback) =
Self::perform_callback(ReceiptEvent::EXPIRED, &mut expired_record_mut) Self::perform_callback(ReceiptEvent::Expired, &mut expired_record_mut)
{ {
callbacks.push(callback) callbacks.push(callback)
} }
@ -342,7 +342,7 @@ impl ReceiptManager {
fn update_next_oldest_timestamp(inner: &mut ReceiptManagerInner) { fn update_next_oldest_timestamp(inner: &mut ReceiptManagerInner) {
// Update the next oldest timestamp // Update the next oldest timestamp
let mut new_next_oldest_ts: Option<u64> = None; let mut new_next_oldest_ts: Option<u64> = None;
for (_, v) in &inner.receipts_by_nonce { for v in inner.receipts_by_nonce.values() {
let receipt_inner = v.lock(); let receipt_inner = v.lock();
if new_next_oldest_ts.is_none() if new_next_oldest_ts.is_none()
|| receipt_inner.expiration_ts < new_next_oldest_ts.unwrap() || receipt_inner.expiration_ts < new_next_oldest_ts.unwrap()
@ -372,7 +372,7 @@ impl ReceiptManager {
// Generate a cancelled callback // Generate a cancelled callback
let callback_future = { let callback_future = {
let mut record_mut = record.lock(); let mut record_mut = record.lock();
Self::perform_callback(ReceiptEvent::CANCELLED, &mut record_mut) Self::perform_callback(ReceiptEvent::Cancelled, &mut record_mut)
}; };
// Issue the callback // Issue the callback
@ -397,7 +397,7 @@ impl ReceiptManager {
// Generate the callback future // Generate the callback future
let mut record_mut = record.lock(); let mut record_mut = record.lock();
record_mut.returns_so_far += 1; record_mut.returns_so_far += 1;
let callback_future = Self::perform_callback(ReceiptEvent::RETURNED, &mut record_mut); let callback_future = Self::perform_callback(ReceiptEvent::Returned, &mut record_mut);
// Remove the record if we're done // Remove the record if we're done
if record_mut.returns_so_far == record_mut.expected_returns { if record_mut.returns_so_far == record_mut.expected_returns {

View File

@ -24,6 +24,6 @@ pub fn decode_node_dial_info_single(
Ok(NodeDialInfoSingle { Ok(NodeDialInfoSingle {
node_id: NodeId::new(node_id), node_id: NodeId::new(node_id),
dial_info: dial_info, dial_info,
}) })
} }

View File

@ -45,6 +45,6 @@ pub fn decode_peer_info(reader: &veilid_capnp::peer_info::Reader) -> Result<Peer
} }
Ok(PeerInfo { Ok(PeerInfo {
node_id: NodeId::new(decode_public_key(&nid_reader)), node_id: NodeId::new(decode_public_key(&nid_reader)),
dial_infos: dial_infos, dial_infos,
}) })
} }

View File

@ -67,7 +67,7 @@ pub fn encode_route_hop(
)?; )?;
if let Some(rhd) = &route_hop.next_hop { if let Some(rhd) = &route_hop.next_hop {
let mut rhd_builder = builder.reborrow().init_next_hop(); let mut rhd_builder = builder.reborrow().init_next_hop();
encode_route_hop_data(&rhd, &mut rhd_builder)?; encode_route_hop_data(rhd, &mut rhd_builder)?;
} }
Ok(()) Ok(())
} }
@ -83,7 +83,7 @@ pub fn encode_private_route(
builder.set_hop_count(private_route.hop_count); builder.set_hop_count(private_route.hop_count);
if let Some(rh) = &private_route.hops { if let Some(rh) = &private_route.hops {
let mut rh_builder = builder.reborrow().init_first_hop(); let mut rh_builder = builder.reborrow().init_first_hop();
encode_route_hop(&rh, &mut rh_builder)?; encode_route_hop(rh, &mut rh_builder)?;
}; };
Ok(()) Ok(())
@ -102,11 +102,11 @@ pub fn encode_safety_route(
match &safety_route.hops { match &safety_route.hops {
SafetyRouteHops::Data(rhd) => { SafetyRouteHops::Data(rhd) => {
let mut rhd_builder = h_builder.init_data(); let mut rhd_builder = h_builder.init_data();
encode_route_hop_data(&rhd, &mut rhd_builder)?; encode_route_hop_data(rhd, &mut rhd_builder)?;
} }
SafetyRouteHops::Private(pr) => { SafetyRouteHops::Private(pr) => {
let mut pr_builder = h_builder.init_private(); let mut pr_builder = h_builder.init_private();
encode_private_route(&pr, &mut pr_builder)?; encode_private_route(pr, &mut pr_builder)?;
} }
}; };
@ -129,10 +129,7 @@ pub fn decode_route_hop_data(
.map_err(map_error_internal!("invalid blob in route hop data"))? .map_err(map_error_internal!("invalid blob in route hop data"))?
.to_vec(); .to_vec();
Ok(RouteHopData { Ok(RouteHopData { nonce, blob })
nonce: nonce,
blob: blob,
})
} }
pub fn decode_route_hop(reader: &veilid_capnp::route_hop::Reader) -> Result<RouteHop, RPCError> { pub fn decode_route_hop(reader: &veilid_capnp::route_hop::Reader) -> Result<RouteHop, RPCError> {
@ -153,8 +150,8 @@ pub fn decode_route_hop(reader: &veilid_capnp::route_hop::Reader) -> Result<Rout
}; };
Ok(RouteHop { Ok(RouteHop {
dial_info: dial_info, dial_info,
next_hop: next_hop, next_hop,
}) })
} }
@ -177,9 +174,9 @@ pub fn decode_private_route(
}; };
Ok(PrivateRoute { Ok(PrivateRoute {
public_key: public_key, public_key,
hop_count: hop_count, hop_count,
hops: hops, hops,
}) })
} }
@ -205,8 +202,8 @@ pub fn decode_safety_route(
}; };
Ok(SafetyRoute { Ok(SafetyRoute {
public_key: public_key, public_key,
hop_count: hop_count, hop_count,
hops: hops, hops,
}) })
} }

View File

@ -28,7 +28,5 @@ pub fn decode_sender_info(
} else { } else {
None None
}; };
Ok(SenderInfo { Ok(SenderInfo { socket_address })
socket_address: socket_address,
})
} }

View File

@ -116,7 +116,7 @@ impl RespondTo {
} }
Self::PrivateRoute(pr) => { Self::PrivateRoute(pr) => {
let mut pr_builder = builder.reborrow().init_private_route(); let mut pr_builder = builder.reborrow().init_private_route();
encode_private_route(&pr, &mut pr_builder)?; encode_private_route(pr, &mut pr_builder)?;
} }
}; };
Ok(()) Ok(())
@ -137,7 +137,7 @@ struct RPCMessageData {
} }
impl ReaderSegments for RPCMessageData { impl ReaderSegments for RPCMessageData {
fn get_segment<'a>(&'a self, idx: u32) -> Option<&'a [u8]> { fn get_segment(&self, idx: u32) -> Option<&[u8]> {
if idx > 0 { if idx > 0 {
None None
} else { } else {
@ -539,12 +539,13 @@ impl RPCProcessor {
) -> Result<(), RPCError> { ) -> Result<(), RPCError> {
let eventual = { let eventual = {
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
inner.waiting_rpc_table.remove(&op_id) inner
.waiting_rpc_table
.remove(&op_id)
.ok_or_else(|| rpc_error_internal("Unmatched operation id"))?
}; };
match eventual { eventual.resolve(rpcreader).await;
None => Err(rpc_error_internal("Unmatched operation id")), Ok(())
Some(e) => Ok(e.resolve(rpcreader).await),
}
} }
// wait for reply // wait for reply
@ -661,11 +662,11 @@ impl RPCProcessor {
out_node_id = sr out_node_id = sr
.hops .hops
.first() .first()
.ok_or(rpc_error_internal("no hop in safety route"))? .ok_or_else(|| rpc_error_internal("no hop in safety route"))?
.dial_info .dial_info
.node_id .node_id
.key; .key;
out = self.wrap_with_route(Some(&sr), private_route, message_vec)?; out = self.wrap_with_route(Some(sr), private_route, message_vec)?;
hopcount = 1 + sr.hops.len(); hopcount = 1 + sr.hops.len();
} }
}; };
@ -700,11 +701,11 @@ impl RPCProcessor {
let out_node_id = sr let out_node_id = sr
.hops .hops
.first() .first()
.ok_or(rpc_error_internal("no hop in safety route"))? .ok_or_else(|| rpc_error_internal("no hop in safety route"))?
.dial_info .dial_info
.node_id .node_id
.key; .key;
out = self.wrap_with_route(Some(&sr), pr_reader, message_vec)?; out = self.wrap_with_route(Some(sr), pr_reader, message_vec)?;
out_node_id out_node_id
} }
} }
@ -746,7 +747,7 @@ impl RPCProcessor {
.network_manager() .network_manager()
.send_envelope(node_ref.clone(), out) .send_envelope(node_ref.clone(), out)
.await .await
.map_err(|e| RPCError::Internal(e)) .map_err(RPCError::Internal)
{ {
// Make sure to clean up op id waiter in case of error // Make sure to clean up op id waiter in case of error
if eventual.is_some() { if eventual.is_some() {
@ -851,7 +852,7 @@ impl RPCProcessor {
out_node_id = sr out_node_id = sr
.hops .hops
.first() .first()
.ok_or(rpc_error_internal("no hop in safety route"))? .ok_or_else(|| rpc_error_internal("no hop in safety route"))?
.dial_info .dial_info
.node_id .node_id
.key; .key;
@ -869,8 +870,7 @@ impl RPCProcessor {
}; };
// Reply with 'route' operation // Reply with 'route' operation
out = out = self.wrap_with_route(safety_route_spec, private_route, reply_vec)?;
self.wrap_with_route(safety_route_spec.clone(), private_route, reply_vec)?;
out_node_id = match safety_route_spec { out_node_id = match safety_route_spec {
None => { None => {
// If no safety route, the first node is the first hop of the private route // If no safety route, the first node is the first hop of the private route
@ -891,7 +891,7 @@ impl RPCProcessor {
// If safety route is in use, first node is the first hop of the safety route // If safety route is in use, first node is the first hop of the safety route
sr.hops sr.hops
.first() .first()
.ok_or(rpc_error_internal("no hop in safety route"))? .ok_or_else(|| rpc_error_internal("no hop in safety route"))?
.dial_info .dial_info
.node_id .node_id
.key .key
@ -919,7 +919,7 @@ impl RPCProcessor {
self.network_manager() self.network_manager()
.send_envelope(node_ref.clone(), out) .send_envelope(node_ref.clone(), out)
.await .await
.map_err(|e| RPCError::Internal(e))?; .map_err(RPCError::Internal)?;
// Reply successfully sent // Reply successfully sent
let send_ts = get_timestamp(); let send_ts = get_timestamp();
@ -971,7 +971,7 @@ impl RPCProcessor {
} }
// xxx: bandwidth limiting here, don't commit to doing info redirects if our network quality sucks // xxx: bandwidth limiting here, don't commit to doing info redirects if our network quality sucks
return true; true
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -1094,7 +1094,7 @@ impl RPCProcessor {
let routing_table = self.routing_table(); let routing_table = self.routing_table();
let protocol_address_type = dial_info.protocol_address_type(); let protocol_address_type = dial_info.protocol_address_type();
let peers = routing_table.get_fast_nodes_of_type(protocol_address_type); let peers = routing_table.get_fast_nodes_of_type(protocol_address_type);
if peers.len() == 0 { if peers.is_empty() {
return Err(rpc_error_internal(format!( return Err(rpc_error_internal(format!(
"no peers of type '{:?}'", "no peers of type '{:?}'",
protocol_address_type protocol_address_type
@ -1222,9 +1222,9 @@ impl RPCProcessor {
.try_into() .try_into()
.map_err(map_error_internal!("invalid closest nodes list length"))?, .map_err(map_error_internal!("invalid closest nodes list length"))?,
); );
for i in 0..closest_nodes.len() { for (i, closest_node) in closest_nodes.iter().enumerate() {
let mut pi_builder = peers_builder.reborrow().get(i as u32); let mut pi_builder = peers_builder.reborrow().get(i as u32);
encode_peer_info(&closest_nodes[i], &mut pi_builder)?; encode_peer_info(closest_node, &mut pi_builder)?;
} }
reply_msg.into_reader() reply_msg.into_reader()
}; };
@ -1440,19 +1440,9 @@ impl RPCProcessor {
} }
async fn rpc_worker(self, receiver: Receiver<RPCMessage>) { async fn rpc_worker(self, receiver: Receiver<RPCMessage>) {
loop { while let Ok(msg) = receiver.recv().await {
let msg = match receiver.recv().await { if let Err(e) = self.process_rpc_message(msg).await {
Ok(v) => v, error!("Couldn't process rpc message: {}", e);
Err(_) => {
break;
}
};
match self.process_rpc_message(msg).await {
Ok(_) => (),
Err(e) => {
error!("Couldn't process rpc message: {}", e);
}
} }
} }
} }
@ -1651,9 +1641,9 @@ impl RPCProcessor {
// Wait for receipt // Wait for receipt
match eventual_value.await { match eventual_value.await {
ReceiptEvent::RETURNED => Ok(true), ReceiptEvent::Returned => Ok(true),
ReceiptEvent::EXPIRED => Ok(false), ReceiptEvent::Expired => Ok(false),
ReceiptEvent::CANCELLED => Err(rpc_error_internal( ReceiptEvent::Cancelled => Err(rpc_error_internal(
"receipt was dropped before expiration".to_owned(), "receipt was dropped before expiration".to_owned(),
)), )),
} }
@ -1685,7 +1675,7 @@ impl RPCProcessor {
} else { } else {
PeerScope::All PeerScope::All
}); });
if own_peer_info.dial_infos.len() == 0 { if own_peer_info.dial_infos.is_empty() {
return Err(rpc_error_internal("No valid public dial info for own node")); return Err(rpc_error_internal("No valid public dial info for own node"));
} }

View File

@ -136,5 +136,5 @@ pub async fn test_all() {
test_enc_dec().await; test_enc_dec().await;
test_dh(crypto).await; test_dh(crypto).await;
shutdown(api.clone()).await; shutdown(api.clone()).await;
assert_eq!(api.is_shutdown(), true); assert!(api.is_shutdown());
} }

View File

@ -1,3 +1,5 @@
#![allow(clippy::bool_assert_comparison)]
use crate::dht::key; use crate::dht::key;
use crate::xx::*; use crate::xx::*;
use core::convert::TryFrom; use core::convert::TryFrom;
@ -104,9 +106,9 @@ pub async fn test_key_conversions() {
// Test default key // Test default key
let (dht_key, dht_key_secret) = (key::DHTKey::default(), key::DHTKeySecret::default()); let (dht_key, dht_key_secret) = (key::DHTKey::default(), key::DHTKeySecret::default());
assert_eq!(dht_key.bytes, EMPTY_KEY); assert_eq!(dht_key.bytes, EMPTY_KEY);
assert_eq!(dht_key.valid, false); assert!(!dht_key.valid);
assert_eq!(dht_key_secret.bytes, EMPTY_KEY_SECRET); assert_eq!(dht_key_secret.bytes, EMPTY_KEY_SECRET);
assert_eq!(dht_key_secret.valid, false); assert!(!dht_key_secret.valid);
let dht_key_string = String::from(&dht_key); let dht_key_string = String::from(&dht_key);
trace!("dht_key_string: {:?}", dht_key_string); trace!("dht_key_string: {:?}", dht_key_string);
let dht_key_string2 = String::from(&dht_key); let dht_key_string2 = String::from(&dht_key);

View File

@ -152,8 +152,7 @@ pub async fn test_cbor(ts: TableStore) {
let d = match db.load_cbor::<key::DHTKey>(0, b"asdf").await { let d = match db.load_cbor::<key::DHTKey>(0, b"asdf").await {
Ok(x) => x, Ok(x) => x,
Err(e) => { Err(e) => {
assert!(false, "couldn't decode cbor: {}", e); panic!("couldn't decode cbor: {}", e);
return;
} }
}; };
assert_eq!(d, Some(dht_key), "keys should be equal"); assert_eq!(d, Some(dht_key), "keys should be equal");

View File

@ -1,3 +1,5 @@
#![allow(clippy::bool_assert_comparison)]
use crate::xx::*; use crate::xx::*;
use crate::*; use crate::*;
cfg_if! { cfg_if! {
@ -227,7 +229,7 @@ pub async fn test_config() {
Ok(()) => (), Ok(()) => (),
Err(e) => { Err(e) => {
error!("Error: {}", e); error!("Error: {}", e);
assert!(false); unreachable!();
} }
} }
let inner = vc.get(); let inner = vc.get();

View File

@ -119,7 +119,7 @@ cfg_if! {
static SETUP_ONCE: Once = Once::new(); static SETUP_ONCE: Once = Once::new();
pub fn setup() -> () { pub fn setup() {
SETUP_ONCE.call_once(|| { SETUP_ONCE.call_once(|| {
let mut cb = ConfigBuilder::new(); let mut cb = ConfigBuilder::new();
cb.add_filter_ignore_str("async_std"); cb.add_filter_ignore_str("async_std");

View File

@ -21,7 +21,7 @@ pub struct NodeId {
} }
impl NodeId { impl NodeId {
pub fn new(key: DHTKey) -> Self { pub fn new(key: DHTKey) -> Self {
Self { key: key } Self { key }
} }
} }
@ -32,14 +32,11 @@ pub struct ValueKey {
} }
impl ValueKey { impl ValueKey {
pub fn new(key: DHTKey) -> Self { pub fn new(key: DHTKey) -> Self {
Self { Self { key, subkey: None }
key: key,
subkey: None,
}
} }
pub fn new_subkey(key: DHTKey, subkey: String) -> Self { pub fn new_subkey(key: DHTKey, subkey: String) -> Self {
Self { Self {
key: key, key,
subkey: if subkey.len() == 0 { subkey: if subkey.len() == 0 {
None None
} else { } else {
@ -55,7 +52,7 @@ pub struct BlockId {
} }
impl BlockId { impl BlockId {
pub fn new(key: DHTKey) -> Self { pub fn new(key: DHTKey) -> Self {
Self { key: key } Self { key }
} }
} }
@ -220,33 +217,19 @@ impl DialInfo {
if let Address::Hostname(_) = address { if let Address::Hostname(_) = address {
panic!("invalid address type for protocol") panic!("invalid address type for protocol")
} }
Self::UDP(DialInfoUDP { Self::UDP(DialInfoUDP { address, port })
address: address,
port: port,
})
} }
pub fn tcp(address: Address, port: u16) -> Self { pub fn tcp(address: Address, port: u16) -> Self {
if let Address::Hostname(_) = address { if let Address::Hostname(_) = address {
panic!("invalid address type for protocol") panic!("invalid address type for protocol")
} }
Self::TCP(DialInfoTCP { Self::TCP(DialInfoTCP { address, port })
address: address,
port: port,
})
} }
pub fn ws(fqdn: String, port: u16, path: String) -> Self { pub fn ws(fqdn: String, port: u16, path: String) -> Self {
Self::WS(DialInfoWS { Self::WS(DialInfoWS { fqdn, port, path })
fqdn: fqdn,
port: port,
path: path,
})
} }
pub fn wss(fqdn: String, port: u16, path: String) -> Self { pub fn wss(fqdn: String, port: u16, path: String) -> Self {
Self::WSS(DialInfoWSS { Self::WSS(DialInfoWSS { fqdn, port, path })
fqdn: fqdn,
port: port,
path: path,
})
} }
pub fn protocol_type(&self) -> ProtocolType { pub fn protocol_type(&self) -> ProtocolType {
match self { match self {
@ -518,9 +501,9 @@ pub struct PeerAddress {
impl PeerAddress { impl PeerAddress {
pub fn new(address: Address, port: u16, protocol_type: ProtocolType) -> Self { pub fn new(address: Address, port: u16, protocol_type: ProtocolType) -> Self {
Self { Self {
address: address, address,
port: port, port,
protocol_type: protocol_type, protocol_type,
} }
} }
@ -554,13 +537,13 @@ pub struct ConnectionDescriptor {
impl ConnectionDescriptor { impl ConnectionDescriptor {
pub fn new(remote: PeerAddress, local: SocketAddr) -> Self { pub fn new(remote: PeerAddress, local: SocketAddr) -> Self {
Self { Self {
remote: remote, remote,
local: Some(local), local: Some(local),
} }
} }
pub fn new_no_local(remote: PeerAddress) -> Self { pub fn new_no_local(remote: PeerAddress) -> Self {
Self { Self {
remote: remote, remote,
local: None, local: None,
} }
} }
@ -642,7 +625,7 @@ impl core::str::FromStr for NodeDialInfoSingle {
// build NodeDialInfoSingle // build NodeDialInfoSingle
Ok(NodeDialInfoSingle { Ok(NodeDialInfoSingle {
node_id: node_id, node_id,
dial_info: match proto { dial_info: match proto {
ProtocolType::UDP => DialInfo::udp(address, port), ProtocolType::UDP => DialInfo::udp(address, port),
ProtocolType::TCP => DialInfo::tcp(address, port), ProtocolType::TCP => DialInfo::tcp(address, port),
@ -853,10 +836,7 @@ pub struct RoutingContext {
impl RoutingContext { impl RoutingContext {
fn new(api: VeilidAPI, options: RoutingContextOptions) -> Self { fn new(api: VeilidAPI, options: RoutingContextOptions) -> Self {
Self { Self {
inner: Arc::new(Mutex::new(RoutingContextInner { inner: Arc::new(Mutex::new(RoutingContextInner { api, options })),
api: api,
options: options,
})),
} }
} }
@ -933,7 +913,7 @@ impl VeilidAPI {
inner: Arc::new(Mutex::new(VeilidAPIInner { inner: Arc::new(Mutex::new(VeilidAPIInner {
config: attachment_manager.config(), config: attachment_manager.config(),
attachment_manager: attachment_manager.clone(), attachment_manager: attachment_manager.clone(),
core: core, core,
network_manager: attachment_manager.network_manager(), network_manager: attachment_manager.network_manager(),
is_shutdown: false, is_shutdown: false,
})), })),
@ -948,9 +928,9 @@ impl VeilidAPI {
self.inner.lock().attachment_manager.clone() self.inner.lock().attachment_manager.clone()
} }
fn network_manager(&self) -> NetworkManager { // fn network_manager(&self) -> NetworkManager {
self.inner.lock().network_manager.clone() // self.inner.lock().network_manager.clone()
} // }
fn rpc_processor(&self) -> RPCProcessor { fn rpc_processor(&self) -> RPCProcessor {
self.inner.lock().network_manager.rpc_processor() self.inner.lock().network_manager.rpc_processor()

View File

@ -164,6 +164,11 @@ pub struct VeilidConfig {
inner: Arc<RwLock<VeilidConfigInner>>, inner: Arc<RwLock<VeilidConfigInner>>,
} }
impl Default for VeilidConfig {
fn default() -> Self {
Self::new()
}
}
impl VeilidConfig { impl VeilidConfig {
fn new_inner() -> VeilidConfigInner { fn new_inner() -> VeilidConfigInner {
VeilidConfigInner::default() VeilidConfigInner::default()

View File

@ -43,6 +43,12 @@ pub struct VeilidCore {
inner: Arc<Mutex<VeilidCoreInner>>, inner: Arc<Mutex<VeilidCoreInner>>,
} }
impl Default for VeilidCore {
fn default() -> Self {
Self::new()
}
}
impl VeilidCore { impl VeilidCore {
fn new_inner() -> VeilidCoreInner { fn new_inner() -> VeilidCoreInner {
VeilidCoreInner { VeilidCoreInner {
@ -58,18 +64,18 @@ impl VeilidCore {
} }
} }
pub(crate) fn config(&self) -> VeilidConfig { // pub(crate) fn config(&self) -> VeilidConfig {
self.inner.lock().config.as_ref().unwrap().clone() // self.inner.lock().config.as_ref().unwrap().clone()
} // }
pub(crate) fn attachment_manager(&self) -> AttachmentManager { // pub(crate) fn attachment_manager(&self) -> AttachmentManager {
self.inner // self.inner
.lock() // .lock()
.attachment_manager // .attachment_manager
.as_ref() // .as_ref()
.unwrap() // .unwrap()
.clone() // .clone()
} // }
pub(crate) fn table_store(&self) -> TableStore { pub(crate) fn table_store(&self) -> TableStore {
self.inner.lock().table_store.as_ref().unwrap().clone() self.inner.lock().table_store.as_ref().unwrap().clone()
@ -119,8 +125,8 @@ impl VeilidCore {
.init(Arc::new( .init(Arc::new(
move |old_state: AttachmentState, new_state: AttachmentState| { move |old_state: AttachmentState, new_state: AttachmentState| {
cb(VeilidStateChange::Attachment { cb(VeilidStateChange::Attachment {
old_state: old_state, old_state,
new_state: new_state, new_state,
}) })
}, },
)) ))

View File

@ -23,6 +23,6 @@ impl RngCore for VeilidRng {
} }
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
intf::random_bytes(dest).map_err(|err| Error::new(err)) intf::random_bytes(dest).map_err(Error::new)
} }
} }

View File

@ -26,6 +26,12 @@ impl EventualBase for Eventual {
} }
} }
impl Default for Eventual {
fn default() -> Self {
Self::new()
}
}
impl Eventual { impl Eventual {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
@ -39,7 +45,7 @@ impl Eventual {
{ {
EventualFutureClone { EventualFutureClone {
id: None, id: None,
value: value, value,
eventual: self.clone(), eventual: self.clone(),
} }
} }

View File

@ -34,7 +34,7 @@ impl<T> EventualBaseInner<T> {
self.wakers.remove(&id); self.wakers.remove(&id);
// See if we should complete the EventualResolvedFutures // See if we should complete the EventualResolvedFutures
let mut resolved_waker_list = Vec::new(); let mut resolved_waker_list = Vec::new();
if self.wakers.len() == 0 && self.resolved.is_some() { if self.wakers.is_empty() && self.resolved.is_some() {
for w in &self.resolved_wakers { for w in &self.resolved_wakers {
resolved_waker_list.push(w.1.clone()); resolved_waker_list.push(w.1.clone());
} }
@ -92,26 +92,25 @@ impl<T> EventualBaseInner<T> {
self.resolved_freelist.clear(); self.resolved_freelist.clear();
} }
pub(super) fn try_reset(&mut self) -> Result<(), ()> { pub(super) fn try_reset(&mut self) -> Result<(), String> {
if self.wakers.len() != 0 { if !self.wakers.is_empty() {
return Err(()); return Err("Wakers not empty during reset".to_owned());
} }
if self.resolved_wakers.len() != 0 { if !self.resolved_wakers.is_empty() {
return Err(()); return Err("Resolved wakers not empty during reset".to_owned());
} }
self.reset(); self.reset();
Ok(()) Ok(())
} }
// Resolved future helpers // Resolved future helpers
#[must_use]
pub(super) fn resolved_poll( pub(super) fn resolved_poll(
&mut self, &mut self,
id: &mut Option<usize>, id: &mut Option<usize>,
cx: &mut task::Context<'_>, cx: &mut task::Context<'_>,
) -> task::Poll<()> { ) -> task::Poll<()> {
// If there are any instance futures still waiting, we resolution isn't finished // If there are any instance futures still waiting, we resolution isn't finished
if self.wakers.len() != 0 { if !self.wakers.is_empty() {
if id.is_none() { if id.is_none() {
*id = Some(self.insert_resolved_waker(cx.waker().clone())); *id = Some(self.insert_resolved_waker(cx.waker().clone()));
} }
@ -137,12 +136,10 @@ impl<T> EventualBaseInner<T> {
*id = Some(self.insert_waker(cx.waker().clone())); *id = Some(self.insert_waker(cx.waker().clone()));
} }
None None
} else if let Some(id) = id.take() {
Some(self.remove_waker(id))
} else { } else {
if let Some(id) = id.take() { Some(Vec::new())
Some(self.remove_waker(id))
} else {
Some(Vec::new())
}
} }
} }
} }
@ -202,7 +199,7 @@ pub trait EventualCommon: EventualBase {
self.base_inner().reset() self.base_inner().reset()
} }
fn try_reset(&self) -> Result<(), ()> { fn try_reset(&self) -> Result<(), String> {
self.base_inner().try_reset() self.base_inner().try_reset()
} }
} }

View File

@ -26,6 +26,12 @@ impl<T: Unpin> EventualBase for EventualValue<T> {
} }
} }
impl<T: Unpin> Default for EventualValue<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Unpin> EventualValue<T> { impl<T: Unpin> EventualValue<T> {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {

View File

@ -26,6 +26,12 @@ impl<T: Unpin + Clone> EventualBase for EventualValueClone<T> {
} }
} }
impl<T: Unpin + Clone> Default for EventualValueClone<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Unpin + Clone> EventualValueClone<T> { impl<T: Unpin + Clone> EventualValueClone<T> {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {

View File

@ -8,10 +8,7 @@ pub struct IpAddrPort {
impl IpAddrPort { impl IpAddrPort {
pub fn new(addr: IpAddr, port: u16) -> Self { pub fn new(addr: IpAddr, port: u16) -> Self {
Self { Self { addr, port }
addr: addr,
port: port,
}
} }
pub fn addr(&self) -> &IpAddr { pub fn addr(&self) -> &IpAddr {
&self.addr &self.addr

View File

@ -63,17 +63,14 @@ pub fn ipv4addr_is_loopback(addr: &Ipv4Addr) -> bool {
pub fn ipv4addr_is_private(addr: &Ipv4Addr) -> bool { pub fn ipv4addr_is_private(addr: &Ipv4Addr) -> bool {
match addr.octets() { match addr.octets() {
[10, ..] => true, [10, ..] => true,
[172, b, ..] if b >= 16 && b <= 31 => true, [172, b, ..] if (16..=31).contains(&b) => true,
[192, 168, ..] => true, [192, 168, ..] => true,
_ => false, _ => false,
} }
} }
pub fn ipv4addr_is_link_local(addr: &Ipv4Addr) -> bool { pub fn ipv4addr_is_link_local(addr: &Ipv4Addr) -> bool {
match addr.octets() { matches!(addr.octets(), [169, 254, ..])
[169, 254, ..] => true,
_ => false,
}
} }
pub fn ipv4addr_is_global(addr: &Ipv4Addr) -> bool { pub fn ipv4addr_is_global(addr: &Ipv4Addr) -> bool {
@ -120,12 +117,10 @@ pub fn ipv4addr_is_broadcast(addr: &Ipv4Addr) -> bool {
} }
pub fn ipv4addr_is_documentation(addr: &Ipv4Addr) -> bool { pub fn ipv4addr_is_documentation(addr: &Ipv4Addr) -> bool {
match addr.octets() { matches!(
[192, 0, 2, _] => true, addr.octets(),
[198, 51, 100, _] => true, [192, 0, 2, _] | [198, 51, 100, _] | [203, 0, 113, _]
[203, 0, 113, _] => true, )
_ => false,
}
} }
pub fn ipv6addr_is_unspecified(addr: &Ipv6Addr) -> bool { pub fn ipv6addr_is_unspecified(addr: &Ipv6Addr) -> bool {
@ -149,10 +144,10 @@ pub fn ipv6addr_is_unique_local(addr: &Ipv6Addr) -> bool {
} }
pub fn ipv6addr_is_unicast_link_local_strict(addr: &Ipv6Addr) -> bool { pub fn ipv6addr_is_unicast_link_local_strict(addr: &Ipv6Addr) -> bool {
(addr.segments()[0] & 0xffff) == 0xfe80 addr.segments()[0] == 0xfe80
&& (addr.segments()[1] & 0xffff) == 0 && addr.segments()[1] == 0
&& (addr.segments()[2] & 0xffff) == 0 && addr.segments()[2] == 0
&& (addr.segments()[3] & 0xffff) == 0 && addr.segments()[3] == 0
} }
pub fn ipv6addr_is_unicast_link_local(addr: &Ipv6Addr) -> bool { pub fn ipv6addr_is_unicast_link_local(addr: &Ipv6Addr) -> bool {

View File

@ -56,8 +56,8 @@ where
fn unlock(&self, jh: Option<JoinHandle<T>>) { fn unlock(&self, jh: Option<JoinHandle<T>>) {
let mut inner = self.inner.lock(); let mut inner = self.inner.lock();
assert_eq!(inner.locked, true); assert!(inner.locked);
assert_eq!(inner.join_handle.is_none(), true); assert!(inner.join_handle.is_none());
inner.locked = false; inner.locked = false;
inner.join_handle = jh; inner.join_handle = jh;
} }

View File

@ -24,7 +24,7 @@ where
pub fn new(drop_value: T) -> Self { pub fn new(drop_value: T) -> Self {
Self { Self {
eventual: EventualValueClone::new(), eventual: EventualValueClone::new(),
drop_value: drop_value, drop_value,
} }
} }

View File

@ -24,7 +24,7 @@ impl TickTask {
pub fn new_us(tick_period_us: u64) -> Self { pub fn new_us(tick_period_us: u64) -> Self {
Self { Self {
last_timestamp_us: AtomicU64::new(0), last_timestamp_us: AtomicU64::new(0),
tick_period_us: tick_period_us, tick_period_us,
routine: OnceCell::new(), routine: OnceCell::new(),
single_future: SingleFuture::new(), single_future: SingleFuture::new(),
} }

View File

@ -1,20 +1,22 @@
use crate::xx::*; use crate::xx::*;
use alloc::string::ToString; use alloc::string::ToString;
pub fn split_port(name: &str) -> Result<(String, u16), ()> { pub fn split_port(name: &str) -> Result<(String, Option<u16>), String> {
if let Some(split) = name.rfind(':') { if let Some(split) = name.rfind(':') {
let hoststr = &name[0..split]; let hoststr = &name[0..split];
let portstr = &name[split + 1..]; let portstr = &name[split + 1..];
let port: u16 = portstr.parse::<u16>().map_err(drop)?; let port: u16 = portstr
.parse::<u16>()
.map_err(|e| format!("Invalid port: {}", e))?;
Ok((hoststr.to_string(), port)) Ok((hoststr.to_string(), Some(port)))
} else { } else {
Err(()) Ok((name.to_string(), None))
} }
} }
pub fn prepend_slash(s: String) -> String { pub fn prepend_slash(s: String) -> String {
if s.starts_with("/") { if s.starts_with('/') {
return s; return s;
} }
let mut out = "/".to_owned(); let mut out = "/".to_owned();