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
use crate::envelope::{MessageEnvelope, NonReturningEnvelope};
use crate::manager::ManagerMessage;
use crate::{Actor, Address, Handler, Message, WeakAddress};
#[cfg(any(
    doc,
    feature = "with-tokio-0_2",
    feature = "with-async_std-1",
    feature = "with-wasm_bindgen-0_2",
    feature = "with-smol-0_1"
))]
use {crate::AddressExt, std::time::Duration};

/// `Context` is used to signal things to the [`ActorManager`](struct.ActorManager.html)'s
/// management loop or to get the actor's address from inside of a message handler.
pub struct Context<A: Actor> {
    /// Whether the actor is running. It is changed by the `stop` method as a flag to the `ActorManager`
    /// for it to call the `stopping` method on the actor
    pub(crate) running: bool,
    /// The address kept by the context to allow for the `Context::address` method to work.
    address: WeakAddress<A>,
    /// Notifications that must be stored for immediate processing.
    pub(crate) immediate_notifications: Vec<Box<dyn MessageEnvelope<Actor = A>>>,
}

impl<A: Actor> Context<A> {
    pub(crate) fn new(address: WeakAddress<A>) -> Self {
        Context {
            running: true,
            address,
            immediate_notifications: Vec::with_capacity(1),
        }
    }

    /// Stop the actor as soon as it has finished processing current message. This will mean that the
    /// [`Actor::stopping`](trait.Actor.html#method.stopping) method will be called.
    /// If that returns [`KeepRunning::No`](enum.KeepRunning.html#variant.No), any subsequent attempts
    /// to send messages to this actor will return the [`Disconnected`](struct.Disconnected.html) error.
    pub fn stop(&mut self) {
        self.running = false;
    }

    /// Get an address to the current actor if the actor is still running.
    pub fn address(&self) -> Option<Address<A>> {
        if self.running {
            let strong = Address {
                sender: self.address.sender.clone(),
                ref_counter: self.address.ref_counter.upgrade().unwrap(),
            };

            Some(strong)
        } else {
            None
        }
    }

    /// Notify this actor with a message that is handled synchronously before any other messages
    /// from the general queue are processed (therefore, immediately). If multiple
    /// `notify_immediately` messages are queued, they will still be processed in the order that they
    /// are queued (i.e the immediate priority is only over other messages).
    pub fn notify_immediately<M>(&mut self, msg: M)
    where
        M: Message,
        A: Handler<M> + Send,
    {
        let envelope = Box::new(NonReturningEnvelope::<A, M>::new(msg));
        self.immediate_notifications.push(envelope);
    }

    /// Notify this actor with a message that is handled synchronously after any other messages
    /// from the general queue are processed.
    pub fn notify_later<M>(&mut self, msg: M)
    where
        M: Message,
        A: Handler<M> + Send,
    {
        let envelope = NonReturningEnvelope::<A, M>::new(msg);
        let _ = self
            .address
            .sender
            .unbounded_send(ManagerMessage::LateNotification(Box::new(envelope)));
    }

    /// Notify the actor with a synchronously handled message every interval until it is stopped
    /// (either directly with [`Context::stop`](struct.Context.html#method.stop), or for a lack of
    /// strong [`Address`es](struct.Address.html)). This does not take priority over other messages.
    ///
    /// ***Only available when using tokio, async_std, smol, or wasm_bindgen.***
    #[cfg(any(
        doc,
        feature = "with-tokio-0_2",
        feature = "with-async_std-1",
        feature = "with-wasm_bindgen-0_2",
        feature = "with-smol-0_1"
    ))]
    pub fn notify_interval<F, M>(&mut self, duration: Duration, constructor: F)
    where
        F: Send + 'static + Fn() -> M,
        M: Message,
        A: Handler<M> + Send,
    {
        let addr = self.address.clone();

        #[cfg(feature = "with-tokio-0_2")]
        tokio::spawn(async move {
            let mut timer = tokio::time::interval(duration);
            loop {
                timer.tick().await;
                if let Err(_) = addr.do_send(constructor()) {
                    break;
                }
            }
        });

        #[cfg(feature = "with-async_std-1")]
        {
            use async_std::prelude::FutureExt;
            async_std::task::spawn(async move {
                loop {
                    futures::future::ready(()).delay(duration.clone()).await;
                    if let Err(_) = addr.do_send(constructor()) {
                        break;
                    }
                }
            });
        }

        #[cfg(feature = "with-wasm_bindgen-0_2")]
        {
            use futures_timer::Delay;
            wasm_bindgen_futures::spawn_local(async move {
                loop {
                    Delay::new(duration.clone()).await;
                    if let Err(_) = addr.do_send(constructor()) {
                        break;
                    }
                }
            })
        }

        #[cfg(feature = "with-smol-0_1")]
        {
            use smol::Timer;
            smol::Task::spawn(async move {
                loop {
                    Timer::after(duration.clone()).await;
                    if let Err(_) = addr.do_send(constructor()) {
                        break;
                    }
                }
            }).detach();
        }
    }

    /// Notify the actor with a synchronously handled message after a certain duration has elapsed.
    /// This does not take priority over other messages.
    ///
    /// ***Only available when using tokio, async_std, smol, or wasm_bindgen.***
    #[cfg(any(
        doc,
        feature = "with-tokio-0_2",
        feature = "with-async_std-1",
        feature = "with-wasm_bindgen-0_2",
        feature = "with-smol-0_1"
    ))]
    pub fn notify_after<M>(&mut self, duration: Duration, notification: M)
    where
        M: Message,
        A: Handler<M> + Send,
    {
        let addr = self.address.clone();

        #[cfg(feature = "with-tokio-0_2")]
        tokio::spawn(async move {
            tokio::time::delay_for(duration).await;
            let _ = addr.do_send(notification);
        });

        #[cfg(feature = "with-async_std-1")]
        {
            use async_std::prelude::FutureExt;
            async_std::task::spawn(async move {
                futures::future::ready(()).delay(duration.clone()).await;
                let _ = addr.do_send(notification);
            });
        }

        #[cfg(feature = "with-wasm_bindgen-0_2")]
        {
            use futures_timer::Delay;
            wasm_bindgen_futures::spawn_local(async move {
                Delay::new(duration.clone()).await;
                let _ = addr.do_send(notification);
            })
        }

        #[cfg(feature = "with-smol-0_1")]
        {
            use smol::Timer;
            smol::Task::spawn(async move {
                Timer::after(duration.clone()).await;
                let _ = addr.do_send(notification);
            }).detach();
        }
    }
}