use std::{future::Future, pin::Pin};
use zbus::message::Flags;
use crate::{BoxDBusError, Connection, DynamicType, Error, fdo, log::trace, message::Message};
pub enum DispatchResult<'a> {
NotFound,
RequiresMut,
Async(Pin<Box<dyn Future<Output = Result<(), BoxDBusError>> + Send + 'a>>),
}
impl<'a> DispatchResult<'a> {
pub fn new_async<F, T, E>(conn: &'a Connection, msg: &'a Message, f: F) -> Self
where
F: Future<Output = ::std::result::Result<T, E>> + Send + 'a,
T: serde::Serialize + DynamicType + Send + Sync,
E: zbus::DBusError + Send,
{
DispatchResult::Async(Box::pin(async move {
let hdr = msg.header();
let ret = f.await;
if !hdr.primary().flags().contains(Flags::NO_REPLY_EXPECTED) {
match ret {
Ok(r) => conn.reply(&hdr, &r).await,
Err(e) => conn.reply_dbus_error(&hdr, e).await,
}
.map(|_seq| ())
.map_err(handler_error)
} else {
trace!("No reply expected for {:?} by the caller.", msg);
Ok(())
}
}))
}
#[doc(hidden)]
pub fn from_handler<F>(f: F) -> Self
where
F: Future<Output = crate::Result<()>> + Send + 'a,
{
DispatchResult::Async(Box::pin(async move { f.await.map_err(handler_error) }))
}
}
#[cold]
fn handler_error(e: Error) -> BoxDBusError {
match e {
Error::FDO(e) => e,
Error::DBus(e) => Box::new(e),
e => Box::new(fdo::Error::Failed(e.to_string())),
}
}