use crate::services::broker::MessageBroker;
use crate::services::handle::{Listen, Serve};
use crate::services::service::Service;
use crate::system_director::SystemDirector;
use crate::{Actor, Receive, Respond};
use async_std::task;
use std::fmt::Debug;
use std::marker::PhantomData;
pub struct ServiceAssistant<S: Service> {
system_director: SystemDirector,
broker: MessageBroker,
phantom_system: PhantomData<S>,
}
impl<S: Service> ServiceAssistant<S> {
pub(crate) fn new(
system_director: SystemDirector,
broker: MessageBroker,
) -> ServiceAssistant<S> {
ServiceAssistant {
system_director,
broker,
phantom_system: PhantomData,
}
}
pub async fn send_to_actor<A: Actor + Receive<M>, M: Debug + Send + 'static>(
&self,
actor_id: A::Id,
message: M,
) {
self.system_director
.send_to_actor::<A, M>(actor_id, message)
.await
}
pub async fn send_to_all_actors<A: Actor + Receive<M>, M: Debug + Send + 'static>(
&self,
message: M,
) {
self.system_director
.send_to_all_actors::<A, M>(message)
.await
}
pub async fn schedule_send_to_actor<A: Actor + Receive<M>, M: Debug + Send + 'static>(
&self,
actor_id: A::Id,
duration: std::time::Duration,
message: M,
) {
self.system_director
.schedule_send_to_actor::<A, M>(actor_id, duration, message)
.await
}
pub async fn schedule_send_to_all_actors<A: Actor + Receive<M>, M: Debug + Send + 'static>(
&self,
duration: std::time::Duration,
message: M,
) {
self.system_director
.schedule_send_to_all_actors::<A, M>(duration, message)
.await
}
pub async fn call_actor<A: Actor + Respond<M>, M: Debug + Send + 'static>(
&self,
actor_id: A::Id,
message: M,
) -> Result<<A as Respond<M>>::Response, &str> {
self.system_director
.call_actor::<A, M>(actor_id, message)
.await
}
pub async fn send_to_service<S1: Service + Listen<M>, M: Debug + Send + 'static>(
&self,
message: M,
) {
self.system_director.send_to_service::<S1, M>(message).await
}
pub async fn call_service<S1: Service + Serve<M>, M: Debug + Send + 'static>(
&self,
message: M,
) -> Result<<S1 as Serve<M>>::Response, &str> {
self.system_director.call_service::<S1, M>(message).await
}
pub fn stop_system(&self) {
let system = self.system_director.clone();
task::spawn(async move {
system.stop().await;
});
}
pub async fn subscribe<M: Sync + Send + Debug + 'static>(&self)
where
S: Service + Listen<M>,
{
self.broker.register::<S, M>();
}
}
impl<S: Service> Clone for ServiceAssistant<S> {
fn clone(&self) -> Self {
ServiceAssistant {
system_director: self.system_director.clone(),
broker: self.broker.clone(),
phantom_system: PhantomData,
}
}
}
impl<S: Service> Debug for ServiceAssistant<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ServiceAssistant Facade for Service")
}
}