Merge pull request #30 from Trivernis/develop

Improved API
pull/32/head
Julius Riegel 3 years ago committed by GitHub
commit 2aeff8eb0e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

2
Cargo.lock generated

@ -93,7 +93,7 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]] [[package]]
name = "bromine" name = "bromine"
version = "0.16.2" version = "0.17.0"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"bincode", "bincode",

@ -1,6 +1,6 @@
[package] [package]
name = "bromine" name = "bromine"
version = "0.16.2" version = "0.17.0"
authors = ["trivernis <trivernis@protonmail.com>"] authors = ["trivernis <trivernis@protonmail.com>"]
edition = "2018" edition = "2018"
readme = "README.md" readme = "README.md"

@ -36,6 +36,9 @@ pub enum Error {
#[error("Unsupported API Version {0}")] #[error("Unsupported API Version {0}")]
UnsupportedVersion(String), UnsupportedVersion(String),
#[error("Invalid state")]
InvalidState,
} }
impl Error { impl Error {

@ -4,10 +4,8 @@ use std::ops::{Deref, DerefMut};
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::atomic::{AtomicUsize, Ordering};
use futures::future;
use futures::future::Either;
use tokio::sync::{Mutex, oneshot, RwLock}; use tokio::sync::{Mutex, oneshot, RwLock};
use tokio::sync::oneshot::Sender; use tokio::sync::oneshot::{Sender, Receiver};
use tokio::time::Duration; use tokio::time::Duration;
use typemap_rev::TypeMap; use typemap_rev::TypeMap;
@ -42,9 +40,9 @@ pub struct Context {
stop_sender: Arc<Mutex<Option<Sender<()>>>>, stop_sender: Arc<Mutex<Option<Sender<()>>>>,
reply_listeners: ReplyListeners, pub(crate) reply_listeners: ReplyListeners,
reply_timeout: Duration, pub default_reply_timeout: Duration,
ref_id: Option<u64>, ref_id: Option<u64>,
@ -66,7 +64,7 @@ impl Context {
reply_listeners, reply_listeners,
data, data,
stop_sender: Arc::new(Mutex::new(stop_sender)), stop_sender: Arc::new(Mutex::new(stop_sender)),
reply_timeout, default_reply_timeout: reply_timeout,
#[cfg(feature = "serialize")] #[cfg(feature = "serialize")]
default_serializer, default_serializer,
ref_id: None, ref_id: None,
@ -74,72 +72,45 @@ impl Context {
} }
/// Emits an event with a given payload that can be serialized into bytes /// Emits an event with a given payload that can be serialized into bytes
pub async fn emit<S: AsRef<str>, P: IntoPayload>( pub fn emit<S: AsRef<str>, P: IntoPayload>(
&self, &self,
name: S, name: S,
payload: P, payload: P,
) -> Result<EmitMetadata> { ) -> EmitMetadata<P> {
let payload_bytes = payload.into_payload(&self)?;
if let Some(ref_id) = &self.ref_id { if let Some(ref_id) = &self.ref_id {
self.emitter self.emitter
.emit_response(*ref_id, name, payload_bytes) .emit_response(self.clone(), *ref_id, name, payload)
.await
} else { } else {
self.emitter.emit(name, payload_bytes).await self.emitter.emit(self.clone(), name, payload)
} }
} }
/// Emits an event to a specific namespace /// Emits an event to a specific namespace
pub async fn emit_to<S1: AsRef<str>, S2: AsRef<str>, P: IntoPayload>( pub fn emit_to<S1: AsRef<str>, S2: AsRef<str>, P: IntoPayload>(
&self, &self,
namespace: S1, namespace: S1,
name: S2, name: S2,
payload: P, payload: P,
) -> Result<EmitMetadata> { ) -> EmitMetadata<P> {
let payload_bytes = payload.into_payload(&self)?;
if let Some(ref_id) = &self.ref_id { if let Some(ref_id) = &self.ref_id {
self.emitter self.emitter
.emit_response_to(*ref_id, namespace, name, payload_bytes) .emit_response_to(self.clone(), *ref_id, namespace, name, payload)
.await
} else { } else {
self.emitter.emit_to(namespace, name, payload_bytes).await self.emitter.emit_to(self.clone(), namespace, name, payload)
} }
} }
/// Waits for a reply to the given message ID /// Registers a reply listener for a given event
#[inline] #[inline]
#[tracing::instrument(level = "debug", skip(self))] #[tracing::instrument(level = "debug", skip(self))]
pub async fn await_reply(&self, message_id: u64) -> Result<Event> { pub(crate) async fn register_reply_listener(&self, event_id: u64) -> Result<Receiver<Event>> {
self.await_reply_with_timeout(message_id, self.reply_timeout.to_owned()).await
}
/// Waits for a reply to the given Message ID with a given timeout
#[tracing::instrument(level = "debug", skip(self))]
pub async fn await_reply_with_timeout(&self, message_id: u64, timeout: Duration) -> Result<Event> {
let (rx, tx) = oneshot::channel(); let (rx, tx) = oneshot::channel();
{ {
let mut listeners = self.reply_listeners.lock().await; let mut listeners = self.reply_listeners.lock().await;
listeners.insert(message_id, rx); listeners.insert(event_id, rx);
} }
let result = future::select( Ok(tx)
Box::pin(tx),
Box::pin(tokio::time::sleep(timeout)),
)
.await;
let event = match result {
Either::Left((tx_result, _)) => Ok(tx_result?),
Either::Right(_) => {
let mut listeners = self.reply_listeners.lock().await;
listeners.remove(&message_id);
Err(Error::Timeout)
}
}?;
Ok(event)
} }
/// Stops the listener and closes the connection /// Stops the listener and closes the connection

@ -1,10 +1,11 @@
use crate::error_event::{ErrorEventData, ERROR_EVENT_NAME}; use std::collections::HashMap;
use std::sync::Arc;
use crate::error_event::{ERROR_EVENT_NAME, ErrorEventData};
use crate::events::event_handler::EventHandler; use crate::events::event_handler::EventHandler;
use crate::namespaces::namespace::Namespace; use crate::namespaces::namespace::Namespace;
use crate::prelude::*; use crate::prelude::*;
use crate::protocol::AsyncProtocolStream; use crate::protocol::AsyncProtocolStream;
use std::collections::HashMap;
use std::sync::Arc;
pub mod builder; pub mod builder;
pub mod client; pub mod client;
@ -65,11 +66,11 @@ fn handle_event(mut ctx: Context, handler: Arc<EventHandler>, event: Event) {
message: format!("{:?}", e), message: format!("{:?}", e),
code: 500, code: 500,
}, },
) ).await
.await
{ {
tracing::error!("Error occurred when sending error response: {:?}", e); tracing::error!("Error occurred when sending error response: {:?}", e);
} }
tracing::error!("Failed to handle event: {:?}", e); tracing::error!("Failed to handle event: {:?}", e);
} }
}); });

@ -1,20 +1,43 @@
use crate::error::Result; use std::future::Future;
use crate::error_event::{ErrorEventData, ERROR_EVENT_NAME}; use std::mem;
use crate::events::event::Event;
use crate::ipc::context::Context;
use crate::protocol::AsyncProtocolStream;
use std::ops::DerefMut; use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::Arc; use std::sync::Arc;
use std::task::Poll;
use std::time::Duration; use std::time::Duration;
use futures::future;
use futures::future::Either;
use tokio::io::{AsyncWrite, AsyncWriteExt}; use tokio::io::{AsyncWrite, AsyncWriteExt};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use tracing;
use crate::error::{Error, Result};
use crate::error_event::{ERROR_EVENT_NAME, ErrorEventData};
use crate::events::event::Event;
use crate::ipc::context::Context;
use crate::payload::IntoPayload;
use crate::protocol::AsyncProtocolStream;
macro_rules! poll_unwrap {
($val:expr) => {
if let Some(v) = $val {
v
} else {
tracing::error!("Polling a future with an invalid state.");
return Poll::Ready(Err(Error::InvalidState))
}
}
}
type SendStream = Arc<Mutex<dyn AsyncWrite + Send + Sync + Unpin + 'static>>;
/// An abstraction over any type that implements the AsyncProtocolStream trait /// An abstraction over any type that implements the AsyncProtocolStream trait
/// to emit events and share a connection across multiple /// to emit events and share a connection across multiple
/// contexts. /// contexts.
#[derive(Clone)] #[derive(Clone)]
pub struct StreamEmitter { pub struct StreamEmitter {
stream: Arc<Mutex<dyn AsyncWrite + Send + Sync + Unpin + 'static>>, stream: SendStream,
} }
impl StreamEmitter { impl StreamEmitter {
@ -24,104 +47,163 @@ impl StreamEmitter {
} }
} }
#[tracing::instrument(level = "trace", skip(self, data_bytes))] #[tracing::instrument(level = "trace", skip(self, ctx, payload))]
async fn _emit( fn _emit<P: IntoPayload>(
&self, &self,
ctx: Context,
namespace: Option<&str>, namespace: Option<&str>,
event: &str, event: &str,
data_bytes: Vec<u8>, payload: P,
res_id: Option<u64>, res_id: Option<u64>,
) -> Result<EmitMetadata> { ) -> EmitMetadata<P> {
let event = if let Some(namespace) = namespace { EmitMetadata::new(ctx, self.stream.clone(), event.to_string(), namespace.map(|n| n.to_string()), payload, res_id)
Event::with_namespace(namespace.to_string(), event.to_string(), data_bytes, res_id)
} else {
Event::new(event.to_string(), data_bytes, res_id)
};
let event_id = event.id();
let event_bytes = event.into_bytes()?;
{
let mut stream = self.stream.lock().await;
stream.deref_mut().write_all(&event_bytes[..]).await?;
tracing::trace!(bytes_len = event_bytes.len());
}
Ok(EmitMetadata::new(event_id))
} }
/// Emits an event /// Emits an event
#[inline] #[inline]
pub(crate) async fn emit<S: AsRef<str>>( pub(crate) fn emit<S: AsRef<str>, P: IntoPayload>(
&self, &self,
ctx: Context,
event: S, event: S,
payload: Vec<u8>, payload: P,
) -> Result<EmitMetadata> { ) -> EmitMetadata<P> {
self._emit(None, event.as_ref(), payload, None).await self._emit(ctx, None, event.as_ref(), payload, None)
} }
/// Emits an event to a specific namespace /// Emits an event to a specific namespace
#[inline] #[inline]
pub(crate) async fn emit_to<S1: AsRef<str>, S2: AsRef<str>>( pub(crate) fn emit_to<S1: AsRef<str>, S2: AsRef<str>, P: IntoPayload>(
&self, &self,
ctx: Context,
namespace: S1, namespace: S1,
event: S2, event: S2,
payload: Vec<u8>, payload: P,
) -> Result<EmitMetadata> { ) -> EmitMetadata<P> {
self._emit(Some(namespace.as_ref()), event.as_ref(), payload, None) self._emit(ctx, Some(namespace.as_ref()), event.as_ref(), payload, None)
.await
} }
/// Emits a response to an event /// Emits a response to an event
#[inline] #[inline]
pub(crate) async fn emit_response<S: AsRef<str>>( pub(crate) fn emit_response<S: AsRef<str>, P: IntoPayload>(
&self, &self,
ctx: Context,
event_id: u64, event_id: u64,
event: S, event: S,
payload: Vec<u8>, payload: P,
) -> Result<EmitMetadata> { ) -> EmitMetadata<P> {
self._emit(None, event.as_ref(), payload, Some(event_id)) self._emit(ctx, None, event.as_ref(), payload, Some(event_id))
.await
} }
/// Emits a response to an event to a namespace /// Emits a response to an event to a namespace
#[inline] #[inline]
pub(crate) async fn emit_response_to<S1: AsRef<str>, S2: AsRef<str>>( pub(crate) fn emit_response_to<S1: AsRef<str>, S2: AsRef<str>, P: IntoPayload>(
&self, &self,
ctx: Context,
event_id: u64, event_id: u64,
namespace: S1, namespace: S1,
event: S2, event: S2,
payload: Vec<u8>, payload: P,
) -> Result<EmitMetadata> { ) -> EmitMetadata<P> {
self._emit( self._emit(
ctx,
Some(namespace.as_ref()), Some(namespace.as_ref()),
event.as_ref(), event.as_ref(),
payload, payload,
Some(event_id), Some(event_id),
) )
.await }
}
struct EventMetadata<P: IntoPayload> {
event: Option<Event>,
ctx: Option<Context>,
event_namespace: Option<Option<String>>,
event_name: Option<String>,
res_id: Option<Option<u64>>,
payload: Option<P>,
}
impl<P: IntoPayload> EventMetadata<P> {
pub fn get_event(&mut self) -> Result<&Event> {
if self.event.is_none() {
self.build_event()?;
}
Ok(self.event.as_ref().unwrap())
}
pub fn take_event(mut self) -> Result<Option<Event>> {
if self.event.is_none() {
self.build_event()?;
}
Ok(mem::take(&mut self.event))
}
fn build_event(&mut self) -> Result<()> {
let ctx = self.ctx.take().ok_or(Error::InvalidState)?;
let event = self.event_name.take().ok_or(Error::InvalidState)?;
let namespace = self.event_namespace.take().ok_or(Error::InvalidState)?;
let payload = self.payload.take().ok_or(Error::InvalidState)?;
let res_id = self.res_id.take().ok_or(Error::InvalidState)?;
let payload_bytes = payload.into_payload(&ctx)?;
let event = if let Some(namespace) = namespace {
Event::with_namespace(namespace.to_string(), event.to_string(), payload_bytes, res_id)
} else {
Event::new(event.to_string(), payload_bytes, res_id)
};
self.event = Some(event);
Ok(())
} }
} }
/// A metadata object returned after emitting an event. /// A metadata object returned after emitting an event.
/// To send the event this object needs to be awaited
/// This object can be used to wait for a response to an event. /// This object can be used to wait for a response to an event.
pub struct EmitMetadata { /// The result contains the emitted event id.
message_id: u64, pub struct EmitMetadata<P: IntoPayload> {
timeout: Option<Duration> event_metadata: Option<EventMetadata<P>>,
stream: Option<SendStream>,
fut: Option<Pin<Box<dyn Future<Output=Result<u64>> + Send>>>,
}
/// A metadata object returned after waiting for a reply to an event
/// This object needs to be awaited for to get the actual reply
pub struct EmitMetadataWithResponse<P: IntoPayload> {
timeout: Option<Duration>,
fut: Option<Pin<Box<dyn Future<Output=Result<Event>>>>>,
emit_metadata: Option<EmitMetadata<P>>,
} }
impl EmitMetadata { impl<P: IntoPayload> EmitMetadata<P> {
#[inline] #[inline]
pub(crate) fn new(message_id: u64) -> Self { pub(crate) fn new(ctx: Context, stream: SendStream, event_name: String, event_namespace: Option<String>, payload: P, res_id: Option<u64>) -> Self {
Self { message_id, timeout: None } Self {
event_metadata: Some(EventMetadata {
event: None,
ctx: Some(ctx),
event_name: Some(event_name),
event_namespace: Some(event_namespace),
payload: Some(payload),
res_id: Some(res_id),
}),
stream: Some(stream),
fut: None,
}
} }
/// The ID of the emitted message /// Waits for a reply to the given message.
#[inline] #[tracing::instrument(skip(self), fields(self.message_id))]
pub fn message_id(&self) -> u64 { pub fn await_reply(self) -> EmitMetadataWithResponse<P> {
self.message_id EmitMetadataWithResponse {
timeout: None,
fut: None,
emit_metadata: Some(self),
}
} }
}
impl<P: IntoPayload> EmitMetadataWithResponse<P> {
/// Sets a timeout for awaiting replies to this emitted event /// Sets a timeout for awaiting replies to this emitted event
#[inline] #[inline]
pub fn with_timeout(mut self, timeout: Duration) -> Self { pub fn with_timeout(mut self, timeout: Duration) -> Self {
@ -129,19 +211,78 @@ impl EmitMetadata {
self self
} }
}
/// Waits for a reply to the given message. impl<P: IntoPayload> Unpin for EmitMetadata<P> {}
#[tracing::instrument(skip(self, ctx), fields(self.message_id))]
pub async fn await_reply(&self, ctx: &Context) -> Result<Event> { impl<P: IntoPayload> Unpin for EmitMetadataWithResponse<P> {}
let reply = if let Some(timeout) = self.timeout {
ctx.await_reply_with_timeout(self.message_id, timeout.clone()).await? impl<P: IntoPayload + 'static> Future for EmitMetadata<P> {
} else { type Output = Result<u64>;
ctx.await_reply(self.message_id).await?
}; fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
if reply.name() == ERROR_EVENT_NAME { if self.fut.is_none() {
Err(reply.payload::<ErrorEventData>()?.into()) let event_metadata = poll_unwrap!(self.event_metadata.take());
} else { let stream = poll_unwrap!(self.stream.take());
Ok(reply)
let event = match event_metadata.take_event() {
Ok(m) => { m }
Err(e) => { return Poll::Ready(Err(e)); }
}.expect("poll after future was done");
self.fut = Some(Box::pin(async move {
let event_id = event.id();
let event_bytes = event.into_bytes()?;
let mut stream = stream.lock().await;
stream.deref_mut().write_all(&event_bytes[..]).await?;
tracing::trace!(bytes_len = event_bytes.len());
Ok(event_id)
}));
} }
self.fut.as_mut().unwrap().as_mut().poll(cx)
} }
} }
impl<P: IntoPayload + 'static> Future for EmitMetadataWithResponse<P> {
type Output = Result<Event>;
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
if self.fut.is_none() {
let mut emit_metadata = poll_unwrap!(self.emit_metadata.take());
let ctx = poll_unwrap!(emit_metadata.event_metadata.as_ref().and_then(|m| m.ctx.clone()));
let timeout = self.timeout.clone().unwrap_or(ctx.default_reply_timeout.clone());
let event_id = match poll_unwrap!(emit_metadata.event_metadata.as_mut()).get_event() {
Ok(e) => { e.id() }
Err(e) => { return Poll::Ready(Err(e)); }
};
self.fut = Some(Box::pin(async move {
let tx = ctx.register_reply_listener(event_id).await?;
emit_metadata.await?;
let result = future::select(
Box::pin(tx),
Box::pin(tokio::time::sleep(timeout)),
)
.await;
let reply = match result {
Either::Left((tx_result, _)) => Ok(tx_result?),
Either::Right(_) => {
let mut listeners = ctx.reply_listeners.lock().await;
listeners.remove(&event_id);
Err(Error::Timeout)
}
}?;
if reply.name() == ERROR_EVENT_NAME {
Err(reply.payload::<ErrorEventData>()?.into())
} else {
Ok(reply)
}
}))
}
self.fut.as_mut().unwrap().as_mut().poll(cx)
}
}

@ -53,7 +53,7 @@
//! .build_client().await.unwrap(); //! .build_client().await.unwrap();
//! //!
//! // emit an initial event //! // emit an initial event
//! let response = ctx.emit("ping", ()).await.unwrap().await_reply(&ctx).await.unwrap(); //! let response = ctx.emit("ping", ()).await_reply().await.unwrap();
//! assert_eq!(response.name(), "pong"); //! assert_eq!(response.name(), "pong");
//! } //! }
//! ``` //! ```

@ -30,4 +30,4 @@ macro_rules! events{
$handler.on($name, callback!($cb)); $handler.on($name, callback!($cb));
)* )*
} }
} }

@ -38,9 +38,7 @@ async fn it_receives_payloads() {
}; };
let reply = ctx let reply = ctx
.emit("ping", payload) .emit("ping", payload)
.await .await_reply()
.unwrap()
.await_reply(&ctx)
.await .await
.unwrap(); .unwrap();
let reply_payload = reply.payload::<SimplePayload>().unwrap(); let reply_payload = reply.payload::<SimplePayload>().unwrap();

@ -47,9 +47,7 @@ async fn it_receives_responses() {
let ctx = get_client_with_server(port).await; let ctx = get_client_with_server(port).await;
let reply = ctx let reply = ctx
.emit("ping", EmptyPayload) .emit("ping", EmptyPayload)
.await .await_reply()
.unwrap()
.await_reply(&ctx)
.await .await
.unwrap(); .unwrap();
let counter = get_counter_from_context(&ctx).await; let counter = get_counter_from_context(&ctx).await;
@ -81,10 +79,8 @@ async fn it_receives_error_responses() {
let ctx = get_client_with_server(port).await; let ctx = get_client_with_server(port).await;
let result = ctx let result = ctx
.emit("create_error", EmptyPayload) .emit("create_error", EmptyPayload)
.await .await_reply()
.unwrap()
.with_timeout(Duration::from_millis(100)) .with_timeout(Duration::from_millis(100))
.await_reply(&ctx)
.await; .await;
let counter = get_counter_from_context(&ctx).await; let counter = get_counter_from_context(&ctx).await;

Loading…
Cancel
Save