Skip to content

Commit

Permalink
sdk: introduce RelayRole
Browse files Browse the repository at this point in the history
  • Loading branch information
yukibtc committed Oct 25, 2023
1 parent e4a3788 commit 70de4cc
Show file tree
Hide file tree
Showing 7 changed files with 195 additions and 87 deletions.
7 changes: 6 additions & 1 deletion crates/nostr-sdk/examples/client-with-opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ async fn main() -> Result<()> {
client.add_relay("wss://relay.damus.io", None).await?;
client.add_relay("wss://nostr.openchain.fr", None).await?;
client
.add_relay_with_opts("wss://nostr.mom", None, RelayOptions::new().write(false))
.add_relay_with_opts(
"wss://nostr.mom",
None,
RelayRole::default(),
RelayOptions::new().write(false),
)
.await?;
client
.add_relay(
Expand Down
9 changes: 7 additions & 2 deletions crates/nostr-sdk/src/client/blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use tokio::sync::broadcast;
#[cfg(feature = "nip46")]
use super::signer::remote::RemoteSigner;
use super::{Entity, Error, Options, TryIntoUrl};
use crate::relay::{pool, Relay, RelayOptions, RelayPoolNotification};
use crate::relay::{pool, Relay, RelayOptions, RelayPoolNotification, RelayRole};
use crate::RUNTIME;

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -143,13 +143,18 @@ impl Client {
&self,
url: U,
proxy: Option<SocketAddr>,
role: RelayRole,
opts: RelayOptions,
) -> Result<bool, Error>
where
U: TryIntoUrl,
pool::Error: From<<U as TryIntoUrl>::Err>,
{
RUNTIME.block_on(async { self.client.add_relay_with_opts(url, proxy, opts).await })
RUNTIME.block_on(async {
self.client
.add_relay_with_opts(url, proxy, role, opts)
.await
})
}

pub fn remove_relay<U>(&self, url: U) -> Result<(), Error>
Expand Down
40 changes: 29 additions & 11 deletions crates/nostr-sdk/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ pub use self::options::Options;
#[cfg(feature = "nip46")]
pub use self::signer::remote::RemoteSigner;
use crate::relay::pool::{self, Error as RelayPoolError, RelayPool};
use crate::relay::{FilterOptions, Relay, RelayOptions, RelayPoolNotification, RelaySendOptions};
use crate::relay::{
FilterOptions, Relay, RelayOptions, RelayPoolNotification, RelayRole, RelaySendOptions,
};
use crate::util::TryIntoUrl;

/// [`Client`] error
Expand Down Expand Up @@ -316,7 +318,7 @@ impl Client {
U: TryIntoUrl,
pool::Error: From<<U as TryIntoUrl>::Err>,
{
self.add_relay_with_opts(url, proxy, RelayOptions::default())
self.add_relay_with_opts(url, proxy, RelayRole::default(), RelayOptions::default())
.await
}

Expand All @@ -327,7 +329,8 @@ impl Client {
U: TryIntoUrl,
pool::Error: From<<U as TryIntoUrl>::Err>,
{
self.add_relay_with_opts(url, RelayOptions::default()).await
self.add_relay_with_opts(url, RelayRole::default(), RelayOptions::default())
.await
}

/// Add new relay with [`Options`]
Expand All @@ -342,7 +345,7 @@ impl Client {
/// # let client = Client::new(&my_keys);
/// let opts = RelayOptions::new().write(false).retry_sec(11);
/// client
/// .add_relay_with_opts("wss://relay.nostr.info", None, opts)
/// .add_relay_with_opts("wss://relay.nostr.info", None, RelayRole::default(), opts)
/// .await
/// .unwrap();
/// # }
Expand All @@ -352,23 +355,29 @@ impl Client {
&self,
url: U,
proxy: Option<SocketAddr>,
role: RelayRole,
opts: RelayOptions,
) -> Result<bool, Error>
where
U: TryIntoUrl,
pool::Error: From<<U as TryIntoUrl>::Err>,
{
Ok(self.pool.add_relay(url, proxy, opts).await?)
Ok(self.pool.add_relay(url, proxy, role, opts).await?)
}

/// Add new relay with [`Options`]
#[cfg(target_arch = "wasm32")]
pub async fn add_relay_with_opts<U>(&self, url: U, opts: RelayOptions) -> Result<bool, Error>
pub async fn add_relay_with_opts<U>(
&self,
url: U,
role: RelayRole,
opts: RelayOptions,
) -> Result<bool, Error>
where
U: TryIntoUrl,
pool::Error: From<<U as TryIntoUrl>::Err>,
{
Ok(self.pool.add_relay(url, opts).await?)
Ok(self.pool.add_relay(url, role, opts).await?)
}

/// Disconnect and remove relay
Expand Down Expand Up @@ -636,7 +645,9 @@ impl Client {
} else {
None
};
self.pool.send_msg(msg, wait).await?;
self.pool
.send_msg(msg, &[RelayRole::default()], wait)
.await?;
Ok(())
}

Expand All @@ -646,7 +657,9 @@ impl Client {
msgs: Vec<ClientMessage>,
wait: Option<Duration>,
) -> Result<(), Error> {
self.pool.batch_msg(msgs, wait).await?;
self.pool
.batch_msg(msgs, &[RelayRole::default()], wait)
.await?;
Ok(())
}

Expand All @@ -673,7 +686,10 @@ impl Client {
let opts = RelaySendOptions::new()
.skip_disconnected(self.opts.get_skip_disconnected_relays())
.timeout(timeout);
Ok(self.pool.send_event(event, opts).await?)
Ok(self
.pool
.send_event(event, &[RelayRole::default()], opts)
.await?)
}

/// Send multiple [`Event`] at once
Expand All @@ -682,7 +698,9 @@ impl Client {
events: Vec<Event>,
opts: RelaySendOptions,
) -> Result<(), Error> {
self.pool.batch_event(events, opts).await?;
self.pool
.batch_event(events, &[RelayRole::default()], opts)
.await?;
Ok(())
}

Expand Down
3 changes: 2 additions & 1 deletion crates/nostr-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ pub use self::client::blocking;
pub use self::client::{Client, Options};
pub use self::relay::{
ActiveSubscription, FilterOptions, InternalSubscriptionId, Relay, RelayConnectionStats,
RelayOptions, RelayPoolNotification, RelayPoolOptions, RelaySendOptions, RelayStatus,
RelayOptions, RelayPoolNotification, RelayPoolOptions, RelayRole, RelaySendOptions,
RelayStatus,
};

#[cfg(feature = "blocking")]
Expand Down
19 changes: 19 additions & 0 deletions crates/nostr-sdk/src/relay/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ use tokio::sync::{broadcast, oneshot, Mutex, RwLock};
pub mod limits;
mod options;
pub mod pool;
mod role;
mod stats;

pub use self::limits::Limits;
pub use self::options::{FilterOptions, RelayOptions, RelayPoolOptions, RelaySendOptions};
use self::options::{MAX_ADJ_RETRY_SEC, MIN_RETRY_SEC};
pub use self::pool::{RelayPoolMessage, RelayPoolNotification};
pub use self::role::RelayRole;
pub use self::stats::RelayConnectionStats;
#[cfg(feature = "blocking")]
use crate::RUNTIME;
Expand Down Expand Up @@ -252,6 +254,7 @@ pub struct Relay {
#[cfg(not(target_arch = "wasm32"))]
proxy: Option<SocketAddr>,
status: Arc<RwLock<RelayStatus>>,
role: Arc<RwLock<RelayRole>>,
#[cfg(feature = "nip11")]
document: Arc<RwLock<RelayInformationDocument>>,
opts: RelayOptions,
Expand All @@ -278,6 +281,7 @@ impl Relay {
#[cfg(not(target_arch = "wasm32"))]
pub fn new(
url: Url,
role: RelayRole,
pool_sender: Sender<RelayPoolMessage>,
notification_sender: broadcast::Sender<RelayPoolNotification>,
proxy: Option<SocketAddr>,
Expand All @@ -290,6 +294,7 @@ impl Relay {
url,
proxy,
status: Arc::new(RwLock::new(RelayStatus::Initialized)),
role: Arc::new(RwLock::new(role)),
#[cfg(feature = "nip11")]
document: Arc::new(RwLock::new(RelayInformationDocument::new())),
opts,
Expand All @@ -310,6 +315,7 @@ impl Relay {
#[cfg(target_arch = "wasm32")]
pub fn new(
url: Url,
role: RelayRole,
pool_sender: Sender<RelayPoolMessage>,
notification_sender: broadcast::Sender<RelayPoolNotification>,
opts: RelayOptions,
Expand All @@ -320,6 +326,7 @@ impl Relay {
Self {
url,
status: Arc::new(RwLock::new(RelayStatus::Initialized)),
role: Arc::new(RwLock::new(role)),
#[cfg(feature = "nip11")]
document: Arc::new(RwLock::new(RelayInformationDocument::new())),
opts,
Expand Down Expand Up @@ -373,6 +380,18 @@ impl Relay {
}
}

/// Get [`RelayRole`]
pub async fn role(&self) -> RelayRole {
let role = self.role.read().await;
role.clone()
}

/// Change [`RelayRole`]
pub async fn change_role(&self, role: RelayRole) {
let mut r = self.role.write().await;
*r = role;
}

/// Check if [`Relay`] is connected
pub async fn is_connected(&self) -> bool {
self.status().await == RelayStatus::Connected
Expand Down
Loading

0 comments on commit 70de4cc

Please sign in to comment.