1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#![allow(dead_code)]

use std::sync::{Arc, Mutex};

use futures::channel::oneshot::{channel, Sender, Receiver, Canceled};
use futures::{Future, Poll, task};

use riker::actors::*;

pub fn ask<Msg, Ctx, T, M>(ctx: &Ctx, receiver: &T, msg: M)
                        -> Box<Future<Item=Msg, Error=Canceled> + Send>
    where Msg: Message,
            M: Into<ActorMsg<Msg>>,
            Ctx: TmpActorRefFactory<Msg=Msg> + ExecutionContext,
            T: Tell<Msg=Msg>
{
    let ask = Ask::new(ctx, receiver.clone(), msg.into());
    let ask = ctx.execute(ask);
    Box::new(ask)
}

pub struct Ask<Msg: Message> {
    inner: Receiver<Msg>,
}

impl<Msg: Message> Ask<Msg> {
    pub fn new<Ctx, T>(ctx: &Ctx, receiver: &T, msg: ActorMsg<Msg>) -> Ask<Msg>
        where Ctx: TmpActorRefFactory<Msg=Msg>, T: Tell<Msg=Msg>
    {
        let (tx, rx) = channel::<Msg>();
        let tx = Arc::new(Mutex::new(Some(tx)));

        let props = Props::new_args(Box::new(AskActor::new), tx);
        let actor = ctx.tmp_actor_of(props).unwrap();
        receiver.tell(msg, Some(actor));

        Ask {
            inner: rx
        }
    }
}

impl<Msg: Message> Future for Ask<Msg> {
    type Item = Msg;
    type Error = Canceled;

    fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> {
        self.inner.poll(cx)
    }
}

struct AskActor<Msg> {
    tx: Arc<Mutex<Option<Sender<Msg>>>>,
}

impl<Msg: Message> AskActor<Msg> {
    fn new(tx: Arc<Mutex<Option<Sender<Msg>>>>) -> BoxActor<Msg> {
        let ask = AskActor {
            tx: tx
        };
        Box::new(ask)
    }
}

impl<Msg: Message> Actor for AskActor<Msg> {
    type Msg = Msg;

    fn receive(&mut self, ctx: &Context<Msg>, msg: Msg, _: Option<ActorRef<Msg>>) {
        if let Ok(mut tx) = self.tx.lock() {
            tx.take().unwrap().send(msg).unwrap();
        }

        ctx.stop(&ctx.myself);
    }
}

#[cfg(test)]
mod tests {
    extern crate riker_default;

    use self::riker_default::DefaultModel;
    use futures::executor::block_on;
    use ask::ask;
    use riker::actors::*;

    #[test]
    /// throw a few thousand asks around
    fn stress_test() {
        #[derive(Debug, Clone)]
        enum Protocol {
            Foo,
            FooResult,
        }

        let system: ActorSystem<Protocol> = {
            let model: DefaultModel<Protocol> = DefaultModel::new();
            ActorSystem::new(&model).unwrap()
        };

        impl Into<ActorMsg<Protocol>> for Protocol {
            fn into(self) -> ActorMsg<Protocol> {
                ActorMsg::User(self)
            }
        }

        struct FooActor;

        impl Actor for FooActor {
            type Msg = Protocol;

            fn receive(
                &mut self,
                context: &Context<Self::Msg>,
                _: Self::Msg,
                sender: Option<ActorRef<Self::Msg>>,
            ) {
                sender.try_tell(
                    Protocol::FooResult,
                    Some(context.myself()),
                ).unwrap();
            }
        }

        impl FooActor {
            fn new() -> FooActor {
                FooActor{}
            }

            fn actor() -> BoxActor<Protocol> {
                Box::new(FooActor::new())
            }

            pub fn props() -> BoxActorProd<Protocol> {
                Props::new(Box::new(FooActor::actor))
            }
        }

        let actor = system
            .actor_of(
                FooActor::props(),
                "foo",
            )
            .unwrap();

        for i in 1..10000 {
            println!("{:?}", i);
            let a = ask(
                &system,
                &actor,
                Protocol::Foo,
            );
            block_on(a).unwrap();
        }
    }

}