Radish alpha
h
Radicle Heartwood Protocol & Stack
Radicle
Git (anonymous pull)
Log in to clone via SSH
protocol: node events
Fintan Halpenny committed 10 months ago
commit 1fde061794ea4dddb8beb8a3949c19bfcd3ab8c5
parent 990c52accf82f248dfa5c59724bc4208358431bb
4 files changed +76 -0
modified crates/radicle-protocol/src/lib.rs
@@ -6,6 +6,7 @@ pub mod worker;

pub mod connections;
pub mod fetcher;
+
pub mod node;
pub mod tasks;

/// Peer-to-peer protocol version.
added crates/radicle-protocol/src/node.rs
@@ -0,0 +1 @@
+
pub mod events;
added crates/radicle-protocol/src/node/events.rs
@@ -0,0 +1,48 @@
+
pub mod emitter;
+

+
use std::collections::VecDeque;
+

+
use radicle::node::Event;
+

+
/// Keep track of [`Event`]s that occur within the rest of the protocol system.
+
///
+
/// The events are queued with [`NodeEvents::push_event`] and removed using
+
/// [`NodeEvents::pop_event`] and [`NodeEvents::drain_events`].
+
///
+
/// To inspect the events use [`NodeEvents::events`].
+
pub struct Events {
+
    events: VecDeque<Event>,
+
}
+

+
impl Extend<Event> for Events {
+
    fn extend<T: IntoIterator<Item = Event>>(&mut self, iter: T) {
+
        self.events.extend(iter);
+
    }
+
}
+

+
impl Events {
+
    /// Push an [`Event`] onto the events queue.
+
    pub fn push_event(&mut self, event: Event) {
+
        self.events.push_back(event);
+
    }
+

+
    /// Pop the next [`Event`] from the events queue.
+
    pub fn pop_event(&mut self) -> Option<Event> {
+
        self.events.pop_front()
+
    }
+

+
    /// Drain the queue of all its events.
+
    ///
+
    /// This is useful for batch processing the available events.
+
    pub fn drain_events(&mut self) -> impl Iterator<Item = Event> + '_ {
+
        self.events.drain(0..self.events.len())
+
    }
+
}
+

+
impl Events {
+
    /// Get the events that are in the queue currently, without modifying the
+
    /// queue itself.
+
    pub fn events(&self) -> impl Iterator<Item = &Event> {
+
        self.events.iter()
+
    }
+
}
added crates/radicle-protocol/src/node/events/emitter.rs
@@ -0,0 +1,26 @@
+
//! An [`Emitter`] captures the ability to emit [`Event`]s to some subscriber
+
//! mechanism.
+

+
use radicle::node::Event;
+

+
use super::Events;
+

+
/// The ability of emit an event to some subscriber mechanism.
+
pub trait Emitter {
+
    /// Emit a single [`Event`], bypassing the need of an events queue.
+
    fn emit(&self, event: Event);
+

+
    /// Emit the next event from the events queue.
+
    fn emit_next(&self, events: &mut Events) {
+
        if let Some(event) = events.pop_event() {
+
            self.emit(event);
+
        }
+
    }
+

+
    /// Emit all the events that are currently on the queue.
+
    fn emit_all(&self, events: &mut Events) {
+
        for event in events.drain_events() {
+
            self.emit(event);
+
        }
+
    }
+
}