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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//! Message Stream Execution Routine and Events
//!
#[cfg(not(feature = "log"))]
use crate::log;
use crate::{
    actor::{Actor, ActorState, Future, Handle},
    context::Context,
    reactor::{inc_poll_budget, pending_polled},
};
use alloc::boxed::Box;
use alloc::sync::Arc;
use core::{
    any::Any,
    pin::Pin,
    task::{Context as CoreContext, Poll},
};
use futures_core::stream::Stream as CoreStream;
use pin_project_lite::pin_project;

/// Message that exchange between actors
///
/// One thing to notice is that this empty
/// trait presents here is
/// - to make a difference between [`Stream<Item>`](crate::stream::Stream)
/// and [`MStream<Message>`](crate::message::MStream)
/// - for future usage
pub trait Message {}

macro_rules! impl_message {
    ($type:ty) => {
        impl Message for $type {}
    };
}

impl_message!(());
impl_message!(bool);
impl_message!(char);
impl_message!(i8);
impl_message!(i16);
impl_message!(i32);
impl_message!(i64);
impl_message!(i128);
impl_message!(isize);
impl_message!(u8);
impl_message!(u16);
impl_message!(u32);
impl_message!(u64);
impl_message!(u128);
impl_message!(usize);
impl<T: Message> Message for Box<T> {}
impl<T: Message> Message for Arc<T> {}
impl<T: Message> Message for Option<T> {}
impl<T: Message, E> Message for Result<T, E> {}

/// An abstraction for Actor's message stream routine
///
pub trait MStream<Item>
where
    Self: Actor,
{
    /// called before the actor emit the first Strem Item
    fn started(&mut self, _: &mut Context<Self>) {}

    /// change the state of stream
    /// to abort/pause/resume the stream accordingly
    ///
    /// Real-Time control or more elaborated
    /// execution could be achieved right here
    fn state(&mut self, _: &mut Context<Self>) -> MStreamingState {
        MStreamingState::Continue
    }

    /// add stream to the actor
    fn spawn_mstream<S>(&mut self, ctx: &mut Context<Self>, stream: S)
    where
        Self: Actor<Message = S::Item> + MStream<S::Item>,
        S: CoreStream + 'static,
        S::Item: Message,
    {
        if ctx.state() == ActorState::Stopped {
            log::error!("Actor Stopped and Unable to add a stream");
        } else {
            ctx.spawn(MStreaming::new(stream));
        }
    }

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

    /// called after the actor pause the stream
    fn paused(&mut self, _: &mut Context<Self>) {}

    /// called after the actor resume the stream
    fn resumed(&mut self, _: &mut Context<Self>) {}

    /// called after the actor send the last Strem Item
    fn finished(&mut self, _: &mut Context<Self>) {}
}

/// Indicator to direct the MStreaming
/// at runtime,
/// - `Continue`: just continue the execution, no
///   intercept happens
/// - `Abort`: intercept the signal and
///   stop blocking immediately
/// - `Pause`: pause the stream
///   and freeze immediately
/// - `Resume`: restore the stream back
///   to `Running`
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum MStreamingState {
    Abort,
    Continue,
    Pause,
    Resume,
}

/// Message stream state
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum MStreamState {
    Created,
    Started,
    Running,
    Aborted,
    Paused,
    Resumed,
    Finished,
}

pin_project! {
    /// streaming a batch of message
    /// and send them to [`Actor::action`](crate::actor::Actor::action)
    pub struct MStreaming<S: CoreStream> {
        #[pin]
        stream: S,
        handle: Handle,
        state: MStreamState,
    }
}

impl<S: CoreStream> MStreaming<S> {
    /// create an instance
    pub fn new(stream: S) -> Self {
        Self {
            stream,
            handle: Handle::new(),
            state: MStreamState::Created,
        }
    }

    /// get the handle
    pub fn handle(&self) -> Handle {
        self.handle
    }

    /// get the state
    #[allow(dead_code)]
    pub fn state(&self) -> MStreamState {
        self.state
    }

    /// set the state
    #[allow(dead_code)]
    pub fn set_state(&mut self, state: MStreamState) {
        self.state = state;
    }
}

impl<A, S> Future<A> for MStreaming<S>
where
    A: Actor<Message = S::Item> + MStream<S::Item>,
    S: CoreStream + 'static,
    S::Item: Message,
{
    type Output = ();

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

        match *this.state {
            // new stream arrives
            MStreamState::Created => {
                let state = <A as MStream<S::Item>>::state(act, ctx);
                // the message Stream state is changed
                // re-poll it
                if *this.state != MStreamState::Created {
                    log::debug!("Message Stream state changed");
                    cx.waker().wake_by_ref();
                    inc_poll_budget(2);
                    return Poll::Pending;
                }
                match state {
                    MStreamingState::Abort => {
                        *this.state = MStreamState::Aborted;
                        log::debug!("Message Stream is Aborting");
                        cx.waker().wake_by_ref();
                        inc_poll_budget(2);
                        return Poll::Pending;
                    }
                    MStreamingState::Pause => {
                        *this.state = MStreamState::Paused;
                        cx.waker().wake_by_ref();
                        inc_poll_budget(2);
                        return Poll::Pending;
                    }
                    _ => {}
                }
                *this.state = MStreamState::Started;
                log::debug!("Message Stream has successfully started");
                cx.waker().wake_by_ref();
                inc_poll_budget(2);
                return Poll::Pending;
            }

            // stream started
            MStreamState::Started => {
                let state = <A as MStream<S::Item>>::state(act, ctx);
                // the Message Stream state is changed
                // re-poll it
                if *this.state != MStreamState::Started {
                    log::debug!("Message Stream state changed");
                    cx.waker().wake_by_ref();
                    inc_poll_budget(2);
                    return Poll::Pending;
                }
                match state {
                    MStreamingState::Abort => {
                        *this.state = MStreamState::Aborted;
                        log::debug!("Message Stream is Aborting");
                        cx.waker().wake_by_ref();
                        inc_poll_budget(2);
                        return Poll::Pending;
                    }
                    MStreamingState::Pause => {
                        *this.state = MStreamState::Paused;
                        cx.waker().wake_by_ref();
                        inc_poll_budget(2);
                        return Poll::Pending;
                    }
                    _ => {}
                }
                *this.state = MStreamState::Running;
                log::debug!("Actor Streaming Message");
                <A as MStream<S::Item>>::started(act, ctx);
                // make sure that stream handle exists
                cx.waker().wake_by_ref();
                inc_poll_budget(2);
                return Poll::Pending;
            }

            // stream is running
            MStreamState::Running => {
                let state = <A as MStream<S::Item>>::state(act, ctx);
                // the Message Stream state is changed
                // re-poll it
                if *this.state != MStreamState::Running {
                    log::debug!("Message Stream state changed");
                    cx.waker().wake_by_ref();
                    inc_poll_budget(2);
                    return Poll::Pending;
                }
                match state {
                    MStreamingState::Abort => {
                        *this.state = MStreamState::Aborted;
                        log::debug!("Message Stream is Aborting");
                        cx.waker().wake_by_ref();
                        inc_poll_budget(2);
                        return Poll::Pending;
                    }
                    MStreamingState::Pause => {
                        *this.state = MStreamState::Paused;
                        cx.waker().wake_by_ref();
                        inc_poll_budget(2);
                        return Poll::Pending;
                    }
                    _ => {}
                }

                match this.stream.as_mut().poll_next(cx) {
                    Poll::Ready(Some(msg)) => {
                        <A as Actor>::action(act, msg, ctx);
                        // the stream state is changed
                        // re-poll it
                        if *this.state != MStreamState::Running {
                            log::debug!("Message Stream state changed");
                            cx.waker().wake_by_ref();
                            inc_poll_budget(2);
                            return Poll::Pending;
                        }
                        Poll::Pending
                    }
                    Poll::Ready(None) => {
                        *this.state = MStreamState::Finished;
                        cx.waker().wake_by_ref();
                        inc_poll_budget(2);
                        Poll::Pending
                    }
                    Poll::Pending => {
                        pending_polled();
                        Poll::Pending
                    }
                }
            }

            // stream get aborted and called to abort the stream
            MStreamState::Aborted => {
                ctx.abort_future(*this.handle);
                <A as MStream<S::Item>>::aborted(act, ctx);
                // the stream state is changed
                // re-poll it
                if *this.state != MStreamState::Aborted {
                    log::debug!("Message Stream state changed");
                    cx.waker().wake_by_ref();
                    inc_poll_budget(2);
                    return Poll::Pending;
                }
                log::debug!("Message Stream is successfully Aborted");
                Poll::Ready(())
            }

            MStreamState::Paused => {
                <A as MStream<S::Item>>::paused(act, ctx);
                log::debug!("Message Stream is successfully Paused");
                let state = <A as MStream<S::Item>>::state(act, ctx);
                // the Message Stream state is changed
                // re-poll it
                if *this.state != MStreamState::Paused {
                    log::debug!("Message Stream state changed");
                    cx.waker().wake_by_ref();
                    inc_poll_budget(2);
                    return Poll::Pending;
                }
                // to check if `abort` is called to stop the stream
                if let MStreamingState::Resume = state {
                    *this.state = MStreamState::Resumed;
                    cx.waker().wake_by_ref();
                    inc_poll_budget(2);
                }
                Poll::Pending
            }

            MStreamState::Resumed => {
                <A as MStream<S::Item>>::resumed(act, ctx);
                // the message stream state is changed
                // re-poll it
                if *this.state != MStreamState::Resumed {
                    log::debug!("Message Stream state changed");
                    cx.waker().wake_by_ref();
                    inc_poll_budget(2);
                    return Poll::Pending;
                }
                log::debug!("Message Stream is successfully Resumed");
                *this.state = MStreamState::Running;
                cx.waker().wake_by_ref();
                inc_poll_budget(2);
                Poll::Pending
            }

            MStreamState::Finished => {
                A::finished(act, ctx);
                // the message stream state is changed
                // re-poll it
                if *this.state != MStreamState::Finished {
                    log::debug!("Message Stream state changed");
                    cx.waker().wake_by_ref();
                    inc_poll_budget(2);
                    return Poll::Pending;
                }
                log::debug!("Message Stream successfully finished");
                Poll::Ready(())
            }
        }
    }

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

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