Skip to content

Commit

Permalink
Introduce a wrapper type RelayDomains
Browse files Browse the repository at this point in the history
  • Loading branch information
sameh-farouk committed Sep 5, 2023
1 parent 6df19bd commit c1606b0
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 15 deletions.
14 changes: 7 additions & 7 deletions src/bins/rmb-peer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::collections::HashSet;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;
Expand All @@ -10,7 +9,7 @@ use rmb::identity::KeyType;
use rmb::identity::{Identity, Signer};
use rmb::peer::Pair;
use rmb::peer::{self, storage::RedisStorage};
use rmb::twin::{SubstrateTwinDB, TwinDB};
use rmb::twin::{SubstrateTwinDB, TwinDB, RelayDomains};
use rmb::{identity, redis};

/// A peer requires only which rely to connect to, and
Expand Down Expand Up @@ -87,11 +86,12 @@ fn parse_urls(input: &[String]) -> Result<Vec<url::Url>> {
}

// maps a &Vec<url::Url> to a HashSet<String> that contains the domain name of each URL
fn get_domains(urls: &[url::Url]) -> HashSet<String> {
urls.iter()
fn get_domains(urls: &[url::Url]) -> RelayDomains {
let h = urls.iter()
.filter_map(|url| url.domain())
.map(|domain| domain.to_string())
.collect()
.collect::<Vec<_>>();
RelayDomains::new(&h)
}

async fn app(args: Params) -> Result<()> {
Expand Down Expand Up @@ -172,8 +172,8 @@ async fn app(args: Params) -> Result<()> {
.ok_or_else(|| anyhow::anyhow!("self twin not found!"))?;

log::debug!("twin relay domain: {:?}", twin.relay);
let onchain_relays: HashSet<String> = twin.relay.unwrap_or_default();
let provided_relays: HashSet<String> = get_domains(&relays_urls);
let onchain_relays = twin.relay.unwrap_or_default();
let provided_relays = get_domains(&relays_urls);
// if twin relay or his pk don't match the ones that
// should be there, we need to set the value on chain
if onchain_relays != provided_relays
Expand Down
5 changes: 2 additions & 3 deletions src/relay/federation/router.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::collections::HashSet;

use crate::{
relay::switch::{Sink, StreamID},
twin::TwinDB,
twin::RelayDomains,
types::Envelope,
};
use anyhow::{Context, Result};
Expand All @@ -29,7 +28,7 @@ where
}
}

async fn try_send<'a>(&self, domains: &'a HashSet<String>, msg: Vec<u8>) -> Result<&'a str> {
async fn try_send<'a>(&self, domains: &'a RelayDomains, msg: Vec<u8>) -> Result<&'a str> {
// TODO: FIX ME
for domain in domains.iter() {
let url = if cfg!(test) {
Expand Down
44 changes: 41 additions & 3 deletions src/twin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ mod substrate;
use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::{collections::HashSet, fmt::{Display, Formatter}, str::FromStr};
pub use substrate::*;
use subxt::utils::AccountId32;

Expand All @@ -19,7 +19,7 @@ use tfchain_client::client::Twin as TwinData;
pub struct Twin {
pub id: u32,
pub account: AccountId32,
pub relay: Option<HashSet<String>>,
pub relay: Option<RelayDomains>,
pub pk: Option<Vec<u8>>,
}

Expand All @@ -30,9 +30,47 @@ impl From<TwinData> for Twin {
account: twin.account_id,
relay: twin.relay.map(|v| {
let string: String = String::from_utf8_lossy(&v.0).into();
string.split('_').map(|s| s.to_string()).collect()
RelayDomains::from_str(&string).unwrap_or_default()
}),
pk: twin.pk.map(|v| v.0),
}
}
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, Eq)]
pub struct RelayDomains(HashSet<String>);

impl FromStr for RelayDomains {
type Err = &'static str;

fn from_str(s: &str) -> Result<Self, Self::Err> {
let set = s.split('_')
.map(|s| s.to_string())
.collect::<HashSet<String>>();
Ok(RelayDomains(set))
}
}

impl Display for RelayDomains {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let s = self.0.iter()
.map(|t| t.to_string())
.collect::<Vec<_>>()
.join("_");
write!(f, "{}", s)
}
}

impl RelayDomains {
pub fn new(inner: &[String]) -> Self {
Self (inner.iter().cloned().collect())
}

pub fn contains(&self, domain: &str) -> bool {
self.0.contains(domain)
}

pub fn iter(&self) -> std::collections::hash_set::Iter<String> {
self.0.iter()
}
}
5 changes: 3 additions & 2 deletions src/twin/substrate.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::RelayDomains;
use super::Twin;
use super::TwinDB;
use crate::cache::Cache;
Expand Down Expand Up @@ -44,12 +45,12 @@ where
pub async fn update_twin(
&self,
kp: &KeyPair,
relay: HashSet<String>,
relay: RelayDomains,
pk: Option<&[u8]>,
) -> Result<()> {
let client = self.client.lock().await;
let hash = client
.update_twin(kp, Some(relay.iter().join("_")), pk)
.update_twin(kp, Some(relay.to_string()), pk)
.await?;
log::debug!("hash: {:?}", hash);
Ok(())
Expand Down

0 comments on commit c1606b0

Please sign in to comment.