From eec5e698d35a42cc9bf52d10bac8c93fe5a3f931 Mon Sep 17 00:00:00 2001 From: trivernis Date: Sun, 8 Nov 2020 16:10:19 +0100 Subject: [PATCH] Change event handling to return multiple events Signed-off-by: trivernis --- Cargo.toml | 2 +- src/event_handler/mod.rs | 18 +++++++----------- src/server/mod.rs | 7 +++---- src/server/server_events.rs | 2 +- 4 files changed, 12 insertions(+), 17 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 726ea5e..4db9ac9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "vented" description = "Event driven encrypted tcp communicaton" -version = "0.5.0" +version = "0.6.0" authors = ["trivernis "] edition = "2018" readme = "README.md" diff --git a/src/event_handler/mod.rs b/src/event_handler/mod.rs index cea2fda..cf58e20 100644 --- a/src/event_handler/mod.rs +++ b/src/event_handler/mod.rs @@ -33,21 +33,17 @@ impl EventHandler { } /// Handles a single event - pub fn handle_event(&mut self, event: Event) -> Option { + pub fn handle_event(&mut self, event: Event) -> Vec { + let mut response_events = Vec::new(); + if let Some(handlers) = self.event_handlers.get(&event.name) { - let mut event = Some(event); for handler in handlers { - if let Some(e) = handler(event.unwrap()) { - event = Some(e); - } else { - event = None; - break; + if let Some(e) = handler(event.clone()) { + response_events.push(e); } } - - event - } else { - None } + + response_events } } diff --git a/src/server/mod.rs b/src/server/mod.rs index 4bae882..dd80412 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -148,9 +148,8 @@ impl VentedServer { } /// Adds a handler for the given event. - /// The event returned by the handler is returned to the server. - /// If there is more than one handler, the response will be piped to the next handler. - /// The oder is by order of insertion. The first registered handler will be executed first. + /// The event returned by the handler is returned to the sender. + /// Multiple handlers can be registered for an event. pub fn on(&mut self, event_name: &str, handler: F) where F: Fn(Event) -> Option + Send + Sync, @@ -299,7 +298,7 @@ impl VentedServer { ) -> VentedResult<()> { while let Ok(mut event) = stream.read() { event.origin = Some(stream.receiver_node().clone()); - if let Some(response) = event_handler.lock().handle_event(event) { + for response in event_handler.lock().handle_event(event) { stream.send(response)? } } diff --git a/src/server/server_events.rs b/src/server/server_events.rs index 0c91525..91d7f61 100644 --- a/src/server/server_events.rs +++ b/src/server/server_events.rs @@ -153,7 +153,7 @@ impl VentedServer { let event_handler = Arc::clone(&event_handler); move || { let response = event_handler.lock().handle_event(event); - let event = response.map(|mut value| { + let event = response.first().cloned().map(|mut value| { Event::with_payload( REDIRECT_EVENT, &RedirectPayload::new(