|
|
|
@ -1,14 +1,38 @@
|
|
|
|
|
use crate::error::Result;
|
|
|
|
|
use crate::events::event::Event;
|
|
|
|
|
use crate::ipc::context::Context;
|
|
|
|
|
use crate::payload::{BytePayload, IntoPayload};
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
use std::fmt::{Debug, Formatter};
|
|
|
|
|
use std::future::Future;
|
|
|
|
|
use std::pin::Pin;
|
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
|
|
|
|
pub struct Response(Vec<u8>);
|
|
|
|
|
|
|
|
|
|
impl Response {
|
|
|
|
|
/// Creates a new response with a given payload
|
|
|
|
|
pub fn payload<P: IntoPayload>(ctx: &Context, payload: P) -> Result<Self> {
|
|
|
|
|
let bytes = payload.into_payload(ctx)?;
|
|
|
|
|
|
|
|
|
|
Ok(Self(bytes))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Creates an empty response
|
|
|
|
|
pub fn empty() -> Self {
|
|
|
|
|
Self(vec![])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub(crate) fn into_byte_payload(self) -> BytePayload {
|
|
|
|
|
BytePayload::new(self.0)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type EventCallback = Arc<
|
|
|
|
|
dyn for<'a> Fn(&'a Context, Event) -> Pin<Box<(dyn Future<Output = Result<()>> + Send + 'a)>>
|
|
|
|
|
dyn for<'a> Fn(
|
|
|
|
|
&'a Context,
|
|
|
|
|
Event,
|
|
|
|
|
) -> Pin<Box<(dyn Future<Output = Result<Response>> + Send + 'a)>>
|
|
|
|
|
+ Send
|
|
|
|
|
+ Sync,
|
|
|
|
|
>;
|
|
|
|
@ -46,7 +70,7 @@ impl EventHandler {
|
|
|
|
|
F: for<'a> Fn(
|
|
|
|
|
&'a Context,
|
|
|
|
|
Event,
|
|
|
|
|
) -> Pin<Box<(dyn Future<Output = Result<()>> + Send + 'a)>>
|
|
|
|
|
) -> Pin<Box<(dyn Future<Output = Result<Response>> + Send + 'a)>>
|
|
|
|
|
+ Send
|
|
|
|
|
+ Sync,
|
|
|
|
|
{
|
|
|
|
@ -56,11 +80,11 @@ impl EventHandler {
|
|
|
|
|
/// Handles a received event
|
|
|
|
|
#[inline]
|
|
|
|
|
#[tracing::instrument(level = "debug", skip(self, ctx, event))]
|
|
|
|
|
pub async fn handle_event(&self, ctx: &Context, event: Event) -> Result<()> {
|
|
|
|
|
pub async fn handle_event(&self, ctx: &Context, event: Event) -> Result<Response> {
|
|
|
|
|
if let Some(cb) = self.callbacks.get(event.name()) {
|
|
|
|
|
cb.as_ref()(ctx, event).await?;
|
|
|
|
|
cb.as_ref()(ctx, event).await
|
|
|
|
|
} else {
|
|
|
|
|
Ok(Response::empty())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|