Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: event bus delete multiple disconnected #281

Merged
merged 1 commit into from
Aug 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 32 additions & 19 deletions crates/relayer/src/event/bus.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use alloc::collections::VecDeque;
use alloc::vec::Vec;

use crossbeam_channel as channel;

pub struct EventBus<T> {
txs: VecDeque<channel::Sender<T>>,
txs: Vec<channel::Sender<T>>,
}

impl<T> Default for EventBus<T> {
Expand All @@ -14,34 +14,22 @@ impl<T> Default for EventBus<T> {

impl<T> EventBus<T> {
pub fn new() -> Self {
Self {
txs: VecDeque::new(),
}
Self { txs: Vec::new() }
}

pub fn subscribe(&mut self) -> channel::Receiver<T> {
let (tx, rx) = channel::unbounded();
self.txs.push_back(tx);
self.txs.push(tx);
rx
}

pub fn broadcast(&mut self, value: T)
where
T: Clone,
{
let mut disconnected = Vec::new();

for (idx, tx) in self.txs.iter().enumerate() {
// TODO: Avoid cloning when sending to last subscriber
if let Err(channel::SendError(_)) = tx.send(value.clone()) {
disconnected.push(idx);
}
}

// Remove all disconnected subscribers
for idx in disconnected {
self.txs.remove(idx);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When there are multiple disconnected receivers, indexes of the latter ones will change after the first receiver is deleted.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's indeed a bug in official Hermes repo

// Send to all txs. Remove disconnected.
self.txs
.retain(|tx| !matches!(tx.send(value.clone()), Err(channel::SendError(_))));
}
}

Expand Down Expand Up @@ -117,4 +105,29 @@ mod tests {

assert_eq!(counter(), 20);
}

#[test]
fn multi_disconnected() {
let mut bus = EventBus::new();

let n = 10;
let mut rxs = vec![];

for _ in 0..n {
rxs.push(bus.subscribe());
}

rxs.remove(0);
rxs.remove(0);

bus.broadcast(42);
for rx in &rxs {
assert_eq!(rx.recv(), Ok(42));
}

bus.broadcast(43);
for rx in &rxs {
assert_eq!(rx.recv(), Ok(43));
}
}
}
Loading