Skip to content

Commit

Permalink
sdk: add uptime stats
Browse files Browse the repository at this point in the history
Check uptime during send event process for disconnected relays
  • Loading branch information
yukibtc committed Oct 5, 2023
1 parent e425408 commit 58a10c0
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
1 change: 1 addition & 0 deletions bindings/nostr-sdk-ffi/src/nostr_sdk.udl
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,7 @@ interface Tag {
interface RelayConnectionStats {
u64 attempts();
u64 success();
f64 uptime();
u64 bytes_sent();
u64 bytes_received();
duration? latency();
Expand Down
4 changes: 4 additions & 0 deletions bindings/nostr-sdk-ffi/src/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ impl RelayConnectionStats {
self.inner.success() as u64
}

pub fn uptime(&self) -> f64 {
self.inner.uptime()
}

pub fn connected_at(&self) -> Arc<Timestamp> {
let secs = self.inner.connected_at().as_u64();
Arc::new(Timestamp::from_secs(secs))
Expand Down
25 changes: 23 additions & 2 deletions crates/nostr-sdk/src/relay/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ use crate::RUNTIME;

type Message = (RelayEvent, Option<oneshot::Sender<bool>>);

const MIN_UPTIME: f64 = 0.90;

/// [`Relay`] error
#[derive(Debug, Error)]
pub enum Error {
Expand Down Expand Up @@ -264,6 +266,17 @@ impl RelayConnectionStats {
self.success.load(Ordering::SeqCst)
}

/// Uptime
pub fn uptime(&self) -> f64 {
let success: f64 = self.success() as f64;
let attempts: f64 = self.attempts() as f64;
if attempts != 0.0 {
success / attempts
} else {
0.0
}
}

/// Bytes sent
pub fn bytes_sent(&self) -> usize {
self.bytes_sent.load(Ordering::SeqCst)
Expand Down Expand Up @@ -1173,7 +1186,11 @@ impl Relay {
pub async fn send_event(&self, event: Event, opts: RelaySendOptions) -> Result<EventId, Error> {
let id: EventId = event.id;

if opts.skip_disconnected && !self.is_connected().await && self.stats.attempts() > 1 {
if opts.skip_disconnected
&& !self.is_connected().await
&& self.stats.attempts() > 1
&& self.stats.uptime() < MIN_UPTIME
{
return Err(Error::EventNotPublished(String::from(
"relay not connected",
)));
Expand Down Expand Up @@ -1240,7 +1257,11 @@ impl Relay {
return Err(Error::BatchEventEmpty);
}

if opts.skip_disconnected && !self.is_connected().await && self.stats.attempts() > 1 {
if opts.skip_disconnected
&& !self.is_connected().await
&& self.stats.attempts() > 1
&& self.stats.uptime() < MIN_UPTIME
{
return Err(Error::EventNotPublished(String::from(
"relay not connected",
)));
Expand Down

0 comments on commit 58a10c0

Please sign in to comment.