#![deny(missing_docs)]
use ghost_actor::*;
#[derive(Debug)]
pub struct Response {
start_index: u32,
finish_index: u32,
}
ghost_chan! {
pub chan MyActorApi<GhostError> {
fn my_api() -> Response;
}
}
pub async fn spawn_my_impl() -> GhostSender<MyActorApi> {
let builder = actor_builder::GhostActorBuilder::new();
let internal_sender = builder
.channel_factory()
.create_channel::<MyInternalApi>()
.await
.unwrap();
let sender = builder
.channel_factory()
.create_channel::<MyActorApi>()
.await
.unwrap();
tokio::task::spawn(builder.spawn(MyImpl {
index: 0,
internal_sender,
}));
sender
}
ghost_chan! {
chan MyInternalApi<GhostError> {
fn finalize_api(start_index: u32) -> Response;
}
}
struct MyImpl {
index: u32,
internal_sender: GhostSender<MyInternalApi>,
}
impl MyImpl {
fn next_index(&mut self) -> u32 {
self.index += 1;
self.index
}
}
impl GhostControlHandler for MyImpl {}
impl GhostHandler<MyActorApi> for MyImpl {}
const DELAY_TIME: &'static [u64] = &[3, 2, 5, 1, 4];
impl MyActorApiHandler for MyImpl {
fn handle_my_api(&mut self) -> MyActorApiHandlerResult<Response> {
let start_index = self.next_index();
let i_s = self.internal_sender.clone();
Ok(must_future::MustBoxFuture::new(async move {
tokio::time::delay_for(std::time::Duration::from_millis(
DELAY_TIME[(start_index % 5) as usize],
))
.await;
i_s.finalize_api(start_index).await
}))
}
}
impl GhostHandler<MyInternalApi> for MyImpl {}
impl MyInternalApiHandler for MyImpl {
fn handle_finalize_api(
&mut self,
start_index: u32,
) -> MyInternalApiHandlerResult<Response> {
let finish_index = self.next_index();
Ok(must_future::MustBoxFuture::new(async move {
Ok(Response {
start_index,
finish_index,
})
}))
}
}
#[tokio::main]
async fn main() {
let actor = spawn_my_impl().await;
let res = futures::future::join_all(
(0..10).map(|_| actor.my_api()).collect::<Vec<_>>(),
)
.await;
println!("{:#?}", res);
}