Skip to content

Overhaul stats: Extract events package (part 3) #1485

Closed

Description

@josecelano

All the duplicated code related to events has been extracted into a new workspace package.

  • Dir: packages/events
  • Crate name: torrust-tracker-events

Now we should make some improvements before using the package in more packages, such as the torrent-repository package.

Subtasks

  • Receiver trait.
  • Decouple Sender and Receiver traits from the tokio broadcast implementation.
  • Return an Option<Arc<...>> instead of an Arc<Option<...>> in the EventBus implementation.
  • Replace Arc<Box<dyn Sender>> with Arc<dyn Sender> to avoid double allocations.
  • Add unit tests.

Decouple Sender and Receiver traits from tokio broadcast implementation

The error SendError is a broadcast-specific tokio::sync::broadcast::error.

pub trait Sender: Sync + Send {
    type Event: Send + Clone;

    fn send_event(&self, event: Self::Event) -> BoxFuture<'_, Option<Result<usize, SendError<Self::Event>>>>;
}

We should wrap that error in our own error type and not expose the internal tokio error.

Return an Option<Arc<...>> instead of an Arc<Option<...>> in the EventBus implementation

Currently:

impl<E: Sync + Send + Clone + 'static> EventBus<E> {

    // ...

    #[must_use]
    pub fn sender(&self) -> Arc<Option<Box<dyn sender::Sender<Event = E>>>> {
        if self.enable_sender {
            Arc::new(Some(Box::new(self.broadcaster.clone())))
        } else {
            Arc::new(None)
        }
    }

    // ...

We propose changing it to:

#[must_use]
pub fn sender(&self) -> Option<Arc<dyn sender::Sender<Event = E>>> {
    if self.enable_sender {
        Some(Arc::new(self.broadcaster.clone()))
    } else {
        None
    }
}

This change makes the optionality clearer, avoids unnecessary heap allocations when enable_sender is false, and simplifies usage.

Example usage:

if let Some(sender) = event_bus.sender() {
    sender.send(my_event);
}

Additionally, by returning Arc<dyn Sender> directly (without a Box), we avoid an extra heap allocation, making the design more efficient and clean.

Activity

  1. self-assigned this
    on Apr 28, 2025
  2. added theissue type on Apr 28, 2025
  3. added 2 commits that reference this issue on Apr 28, 2025
  4. added 10 commits that reference this issue on Apr 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Code Cleanup / Refactoring

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions