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
//! An abstraction for a computational entity
//!
use core::{
    any::Any,
    future::Future as CoreFuture,
    marker::PhantomData,
    pin::Pin,
    sync::atomic::{AtomicUsize, Ordering},
    task::{Context as CoreContext, Poll},
};
use pin_project_lite::pin_project;

#[cfg(not(feature = "log"))]
use crate::log;
use crate::{
    address::Addr,
    context::Context,
    message::Message,
    register::{ActorRegister, Register},
};

/// Actor State
#[derive(PartialEq, Clone, Debug)]
pub enum ActorState {
    Created,
    Started,
    Running,
    Aborted,
    //Paused,
    //Resumed,
    Stopping,
    Stopped,
}

/// Indicator to direct the Actor
/// at runtime,
/// - `Continue`: just continue the execution, no
///   intercept happens
/// - `Abort`: intercept the signal and
///   exit execution immediately
/// - `Stop`: intercept the execution and
///   step the actor into `Stopping` state
///   if `Resume` is not returned following, then
///   the actor get `Stopped`
/// - `Resume`: restore the Actor back
///   to `Running` from `Stopping` state
#[derive(PartialEq, Clone, Debug)]
pub enum ActingState {
    Continue,
    Abort,
    Resume,
    Stop,
}

impl ActorState {
    pub fn is_running(&self) -> bool {
        *self == ActorState::Running || *self == ActorState::Stopping
    }

    pub fn is_stopping(&self) -> bool {
        *self == ActorState::Stopping || *self == ActorState::Stopped
    }

    pub fn is_started(&self) -> bool {
        *self != Self::Created
    }
}

static HANDLECOUNT: AtomicUsize = AtomicUsize::new(1);

/// An unique identifier
///
/// **NOTE** that if the inner id is `0`
/// it means that the returned
/// handle is **INVALID**, and the
/// corresponding task not spawned
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Handle(usize);

impl Handle {
    pub(crate) fn new() -> Self {
        Self(HANDLECOUNT.fetch_add(1, Ordering::Relaxed))
    }

    pub fn inner(self) -> usize {
        self.0
    }

    pub fn is_valid(&self) -> bool {
        self.0 != 0
    }
}

/// An abstraction for Actor's Future routine
///
pub trait Future<A>
where
    A: Actor,
{
    /// the returned type of value when the future polled successfully
    type Output;

    fn poll(
        self: Pin<&mut Self>,
        act: &mut A,
        ctx: &mut Context<A>,
        cx: &mut CoreContext<'_>,
    ) -> Poll<Self::Output>;

    fn downcast_ref(&self) -> Option<&dyn Any>;

    fn downcast_mut(self: Pin<&mut Self>) -> Option<Pin<&mut dyn Any>>;
}

impl<A: Actor, F, Output> Future<A> for F
where
    F: Unpin + FnMut(&mut A, &mut Context<A>, &mut CoreContext<'_>) -> Poll<Output>,
{
    type Output = Output;

    fn poll(
        mut self: Pin<&mut Self>,
        act: &mut A,
        ctx: &mut Context<A>,
        cx: &mut CoreContext<'_>,
    ) -> Poll<Self::Output> {
        (self)(act, ctx, cx)
    }

    fn downcast_ref(&self) -> Option<&dyn Any> {
        None
    }

    fn downcast_mut(self: Pin<&mut Self>) -> Option<Pin<&mut dyn Any>> {
        None
    }
}

pin_project! {
    /// A Converter of normal future into
    /// actor Future
    pub struct Localizer<A, F>
    where
        A: Actor,
        F: CoreFuture
    {
        #[pin]
        future: F,
        _data: PhantomData<A>,
    }
}

impl<A, F> Localizer<A, F>
where
    F: CoreFuture,
    A: Actor,
{
    pub fn new(future: F) -> Self {
        Localizer {
            future,
            _data: PhantomData,
        }
    }
}

impl<A, F> Future<A> for Localizer<A, F>
where
    F: CoreFuture,
    A: Actor,
{
    type Output = F::Output;

    fn poll(
        self: Pin<&mut Self>,
        _: &mut A,
        _: &mut Context<A>,
        cx: &mut CoreContext<'_>,
    ) -> Poll<Self::Output> {
        self.project().future.poll(cx)
    }

    fn downcast_ref(&self) -> Option<&dyn Any> {
        None
    }

    fn downcast_mut(self: Pin<&mut Self>) -> Option<Pin<&mut dyn Any>> {
        None
    }
}

/// unique actor id,
///
/// **NOTE** that each actor is assigned
/// an unique id after [`Actor::start`](Actor::start)
///
/// and store it into [Context](Context)
pub type ActorId = usize;

/// An abstraction for a computational entity
///
pub trait Actor: Sized + Unpin + 'static {
    type Message: Message;

    /// create a instance of an actor
    fn create(ctx: &mut Context<Self>) -> Self;

    /// preparation before start the actor
    /// it get executed before `Actor::state`
    /// gets called.  That means it is called even
    /// `Actor::state` return `ActingState::Abort`
    ///
    /// even if the actor state is changed
    /// after executing it
    /// it is ignored though anyway
    /// the actor should step into Started state
    /// for this state change
    fn initial(&mut self, _: &mut Context<Self>) {}

    /// start the actor
    /// it basically does the following things:
    /// - Create the default context
    /// - Create the actor instance
    /// - consume the Actor to Create an ActorRegister
    /// - Register the Actor and return the ActorGuard
    /// - Invoke ContextRunner to run the actor
    fn start() -> (Addr<Self::Message>, ActorId) {
        let mut ctx = Context::new();
        let act = Self::create(&mut ctx);
        let reg = ActorRegister::new(act);
        let id = reg.id();
        ctx.set_id(id);
        let actor = Register::push(reg);
        (ctx.run(actor), id)
    }

    /// called when the actor starts but not running
    fn started(&mut self, _: &mut Context<Self>) {}

    /// make a reaction when the message comes
    /// called when the actor received message
    fn action(&mut self, msg: Self::Message, ctx: &mut Context<Self>);

    /// to decide whether to resume/stop/continue the actor
    /// the actor will step into `Stopping` phase if `Stop`
    /// is returned
    /// and actor will be stopped if `Resume` is not returned
    /// when it is in stopping phase
    ///
    /// Real-Time control or more elaborated
    /// execution could be achieved right here
    fn state(&mut self, _: &mut Context<Self>) -> ActingState {
        ActingState::Continue
    }

    /// called when the actor get aborted
    fn aborted(&mut self, _: &mut Context<Self>) {}

    /// called when the actor is stopping but not to exit
    /// the actor can restore running state from stopped state
    fn stopped(&mut self, _: &mut Context<Self>) {}

    /// final work before exit
    /// it will be called even the actor gets aborted
    /// after this, the actor is terminated
    ///
    /// even if the actor state is changed
    /// after executing it
    /// it is ignored though anyway
    /// the actor will respond to state change
    /// before `Actor::close`
    fn close(&mut self, ctx: &mut Context<Self>) {
        let id = ctx.id();
        Register::get(id).map(|en| en.set_closed(true));
        log::debug!("mark the actor register closed");
    }
}