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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
use std;
use futures::{Future, Async, Poll, Stream};

use actor::{Actor, Supervised, AsyncContext};
use arbiter::Arbiter;
use address::{Address, SyncAddress};
use context::{Context, ContextProtocol, AsyncContextApi};
use envelope::Envelope;
use msgs::Execute;
use queue::{sync, unsync};

/// Actor supervisor
///
/// Supervisor manages incomimng message for actor. In case of actor failure, supervisor
/// creates new execution context and restarts actor lifecycle. Actor can be
/// constructed lazily.
///
/// Supervisor has same livecycle as actor. In situation when all addresses to supervisor
/// get dropped and actor does not execution anything supervisor terminates.
///
/// `Supervisor` can not garantee that actor successfully process incoming message.
/// If actor fails during message processing, this message can not be recovered. Sender
/// would receive `Err(Cancelled)` error in this situation.
///
/// ## Example
///
/// ```rust
/// extern crate actix;
///
/// use actix::prelude::*;
///
/// // message
/// struct Die;
///
/// impl ResponseType for Die {
///     type Item = ();
///     type Error = ();
/// }
///
/// struct MyActor;
///
/// impl Actor for MyActor {
///     type Context = Context<Self>;
/// }
///
/// // To use actor with supervisor actor has to implement `Supervised` trait
/// impl Supervised for MyActor {
///     fn restarting(&mut self, ctx: &mut Context<MyActor>) {
///         println!("restarting");
///     }
/// }
///
/// impl Handler<Die> for MyActor {
///
///     fn handle(&mut self, _: Die, ctx: &mut Context<MyActor>) -> Response<Self, Die> {
///         ctx.stop();
///         Arbiter::system().send(msgs::SystemExit(0));
///         Self::empty()
///     }
/// }
///
/// fn main() {
///     let sys = System::new("test");
///
///     let (addr, _) = Supervisor::start(false, |_| MyActor);
///
///     addr.send(Die);
///     sys.run();
/// }
/// ```
pub struct Supervisor<A: Supervised> where A: Actor<Context=Context<A>> {
    cell: Option<ActorCell<A>>,
    factory: Option<Box<FnFactory<A>>>,
    msgs: unsync::UnboundedReceiver<ContextProtocol<A>>,
    sync_msgs: sync::UnboundedReceiver<Envelope<A>>,
    msg: Option<ContextProtocol<A>>,
    sync_msg: Option<Envelope<A>>,
    sync_alive: bool,
}

struct ActorCell<A: Supervised> {
    ctx: A::Context,
    addr: unsync::UnboundedSender<ContextProtocol<A>>,
}

impl<A> Supervisor<A> where A: Supervised + Actor<Context=Context<A>>
{
    /// Start new supervised actor. Depends on `lazy` argument actor could be started
    /// immidietly or on first incoming message.
    pub fn start<F>(lazy: bool, f: F) -> (Address<A>, SyncAddress<A>)
        where A: Actor<Context=Context<A>>,
              F: FnOnce(&mut A::Context) -> A + 'static
    {
        // create actor
        let (cell, factory) = if !lazy {
            let mut ctx = Context::new(unsafe{std::mem::uninitialized()});
            let addr = ctx.address_cell().unsync_sender();
            let act = f(&mut ctx);
            let old = ctx.replace_actor(act);
            std::mem::forget(old);
            (Some(ActorCell{ctx: ctx, addr: addr}), None)
        } else {
            let f: Box<FnFactory<A>> = Box::new(f);
            (None, Some(f))
        };

        // create supervisor
        let rx = unsync::unbounded();
        let (stx, srx) = sync::unbounded();
        let mut supervisor = Supervisor {
            cell: cell,
            factory: factory,
            msgs: rx,
            sync_msgs: srx,
            msg: None,
            sync_msg: None,
            sync_alive: true,
        };
        let addr = Address::new(supervisor.msgs.sender());
        let saddr = SyncAddress::new(stx);
        Arbiter::handle().spawn(supervisor);

        (addr, saddr)
    }

    /// Start new supervised actor in arbiter's thread. Depends on `lazy` argument
    /// actor could be started immidietly or on first incoming message.
    pub fn start_in<F>(addr: SyncAddress<Arbiter>, lazy: bool, f: F) -> Option<SyncAddress<A>>
        where A: Actor<Context=Context<A>>,
              F: FnOnce(&mut Context<A>) -> A + Send + 'static
    {
        if addr.connected() {
            let (tx, rx) = sync::unbounded();

            addr.send(Execute::new(move || -> Result<(), ()> {
                // create actor
                let (cell, factory) = if lazy {
                    let mut ctx = Context::new(unsafe{std::mem::uninitialized()});
                    let addr = ctx.address_cell().unsync_sender();
                    let act = f(&mut ctx);
                    let old = ctx.replace_actor(act);
                    std::mem::forget(old);
                    (Some(ActorCell{ctx: ctx, addr: addr}), None)
                } else {
                    let f: Box<FnFactory<A>> = Box::new(f);
                    (None, Some(f))
                };

                let lrx = unsync::unbounded();
                let supervisor = Supervisor {
                    cell: cell,
                    factory: factory,
                    msgs: lrx,
                    sync_msgs: rx,
                    msg: None,
                    sync_msg: None,
                    sync_alive: true,
                };
                Arbiter::handle().spawn(supervisor);
                Ok(())
            }));

            if addr.connected() {
                Some(SyncAddress::new(tx))
            } else {
                None
            }
        } else {
            None
        }
    }

    fn get_cell(&mut self) -> &mut ActorCell<A> {
        if self.cell.is_none() {
            let f = self.factory.take().expect("Should be available");
            let mut ctx = Context::new(unsafe{std::mem::uninitialized()});

            let addr = ctx.address_cell().unsync_sender();
            let act = f.call(&mut ctx);
            let old = ctx.replace_actor(act);
            std::mem::forget(old);

            self.cell = Some(ActorCell {ctx: ctx, addr: addr});
        }
        self.cell.as_mut().unwrap()
    }

    fn restart(&mut self) {
        let cell = self.cell.take().unwrap();
        let mut ctx = Context::new(unsafe{std::mem::uninitialized()});

        let addr = ctx.address_cell().unsync_sender();
        let old = ctx.replace_actor(cell.ctx.into_inner());
        std::mem::forget(old);
        ctx.restarting();

        self.cell = Some(ActorCell {ctx: ctx, addr: addr});
    }
}

#[doc(hidden)]
impl<A> Future for Supervisor<A> where A: Supervised + Actor<Context=Context<A>>
{
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            // poll supervised actor
            if self.cell.is_some() {
                match self.get_cell().ctx.poll() {
                    Ok(Async::NotReady) => (),
                    Ok(Async::Ready(_)) | Err(_) => {
                        self.restart();
                    }
                }
            }

            let mut not_ready = true;

            // check messages
            if let Some(msg) = self.msg.take() {
                match msg {
                    ContextProtocol::Upgrade(_) => (),
                    // if Actor message queue is dead, store in temp
                    msg => {
                        if let Err(msg) = self.get_cell().addr.unbounded_send(msg) {
                            self.msg = Some(msg.into_inner());
                        }
                    }
                }
            }
            if self.msg.is_none() {
                match self.msgs.poll() {
                    Ok(Async::Ready(Some(msg))) => {
                        not_ready = false;
                        match msg {
                            ContextProtocol::Upgrade(tx) => {
                                self.sync_alive = true;
                                let _ = tx.send(SyncAddress::new(self.sync_msgs.sender()));
                            }
                            // if Actor message queue is dead, store in temp
                            msg => {
                                if let Err(msg) = self.get_cell().addr.unbounded_send(msg) {
                                    self.msg = Some(msg.into_inner());
                                }
                            },
                        }
                    }
                    Ok(Async::NotReady) | Ok(Async::Ready(None)) | Err(_) => (),
                }
            }

            // check remote messages. we still use local queue for remote message,
            // because actor runs in same context as supervisor
            if let Some(msg) = self.sync_msg.take() {
                // if Actor message queue is dead, store in temp
                if let Err(msg) = self.get_cell().addr.unbounded_send(
                    ContextProtocol::Envelope(msg))
                {
                    if let ContextProtocol::Envelope(msg) = msg.into_inner() {
                        self.sync_msg = Some(msg);
                    }
                }
            }
            if self.sync_msg.is_none() {
                match self.sync_msgs.poll() {
                    Ok(Async::Ready(Some(msg))) => {
                        not_ready = false;
                        if let Err(msg) = self.get_cell().addr.unbounded_send(
                            ContextProtocol::Envelope(msg))
                        {
                            if let ContextProtocol::Envelope(msg) = msg.into_inner() {
                                self.sync_msg = Some(msg);
                            }
                        }
                    },
                    Ok(Async::NotReady) => (),
                    Ok(Async::Ready(None)) | Err(_) => {
                        self.sync_alive = false
                    }
                }
            }

            // are we done
            if not_ready {
                return Ok(Async::NotReady)
            }

            // poll supervised actor
            match self.get_cell().ctx.poll() {
                Ok(Async::NotReady) => (),
                Ok(Async::Ready(_)) | Err(_) => {
                    // supervisor disconnected
                    if !self.get_cell().ctx.alive() &&
                        !self.msgs.connected() &&
                        !self.sync_alive
                    {
                        return Ok(Async::Ready(()))
                    }
                    self.restart();
                }
            }
        }
    }
}

trait FnFactory<A: Actor>: 'static where A::Context: AsyncContext<A> {
    fn call(self: Box<Self>, &mut A::Context) -> A;
}

impl<A: Actor, F: FnOnce(&mut A::Context) -> A + 'static> FnFactory<A> for F
    where A::Context: AsyncContext<A>
{
    #[cfg_attr(feature="cargo-clippy", allow(boxed_local))]
    fn call(self: Box<Self>, ctx: &mut A::Context) -> A {
        (*self)(ctx)
    }
}