lakka 0.1.0

Simple actors with macros
Documentation
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use std::future::{ready, Ready};
use std::{fmt, future::Future, pin::Pin};
pub mod channel;

//mod actor;
mod channels;
pub use self::channel::mpsc::*;
//pub use actor::*;
pub use channels::delayed_message::DelayedMessage;
pub use channels::interval_channel::{IntervalMessage, Intervaller};
pub use channels::singleshot::Singleshot;

use channel::mpsc;
use futures::FutureExt;
pub use lakka_macro::messages;
use tokio::sync::broadcast;

#[derive(Debug)]
pub enum Message<Ask, Tell> {
    Ask(Ask),
    Tell(Tell),
}

pub trait ActorHandle<T> {
    fn new(tx: Box<dyn ChannelSender<T>>) -> Self;
}
pub trait UnboundedActorHandle<T> {
    fn new(tx: Box<dyn UnboundedChannelSender<T>>) -> Self;
}

pub type UnboundedActorSender<T> = Box<dyn UnboundedChannelSender<T>>;
pub type ActorSender<T> = Box<dyn ChannelSender<T>>;
type ActorReceiver<T> = Box<dyn Channel<T>>;

//impl <T: UnboundedActor> Actor for T {
pub trait UnboundedActor: Actor {
    type Handle: UnboundedActorHandle<Message<Self::Ask, Self::Tell>> + fmt::Debug;

    fn run(self) -> <Self as UnboundedActor>::Handle {
        <Self as UnboundedActor>::run_with_channels(self, vec![])
    }

    fn run_with_channels(
        self,
        extra_channel_receivers: Vec<Box<dyn Channel<<Self as Actor>::Tell>>>,
    ) -> <Self as UnboundedActor>::Handle {
        let (tx, rx) = crate::mpsc::unbounded_channel::<<Self as ActorMessage>::Message>();
        let rx = Box::new(rx);
        let tx = Box::new(tx);
        self.run_task(rx, extra_channel_receivers);
        <Self as UnboundedActor>::Handle::new(tx)
    }
}

pub trait BoundedActor: Actor {
    type Handle: ActorHandle<Message<Self::Ask, Self::Tell>> + fmt::Debug;

    fn run(self) -> <Self as BoundedActor>::Handle {
        self.run_bounded(100, vec![])
    }

    fn run_with_channels(
        self,
        extra_channel_receivers: Vec<Box<dyn Channel<<Self as Actor>::Tell>>>,
    ) -> <Self as BoundedActor>::Handle {
        self.run_bounded(100, extra_channel_receivers)
    }

    fn run_bounded(
        self,
        limit: usize,
        extra_channel_receivers: Vec<Box<dyn Channel<<Self as Actor>::Tell>>>,
    ) -> <Self as BoundedActor>::Handle {
        let (tx, rx) = crate::mpsc::channel::<<Self as ActorMessage>::Message>(limit);
        let rx = Box::new(rx);
        let tx = Box::new(tx);
        self.run_task(rx, extra_channel_receivers);
        <Self as BoundedActor>::Handle::new(tx)
    }
}

pub trait Actor: Sized + Send + 'static {
    type Ask: Send;
    type Tell: Clone + Send + fmt::Debug;

    fn handle_asks(
        &mut self,
        msg: Self::Ask,
        _ctx: &mut ActorContext<Self>,
    ) -> impl Future<Output = ()> + Send;
    fn handle_tells(
        &mut self,
        msg: Self::Tell,
        _ctx: &mut ActorContext<Self>,
    ) -> impl Future<Output = ()> + Send;

    fn handle_message(
        &mut self,
        msg: Message<Self::Ask, Self::Tell>,
        mut _ctx: &mut ActorContext<Self>,
    ) -> impl Future<Output = ()> + Send {
        async move {
            match msg {
                Message::Ask(ask_msg) => self.handle_asks(ask_msg, _ctx).await,
                Message::Tell(tell_msg) => self.handle_tells(tell_msg, _ctx).await,
            }
        }
    }

    fn run_task(
        mut self,
        rx: ActorReceiver<<Self as ActorMessage>::Message>,
        mut extra_channel_receivers: Vec<Box<dyn Channel<<Self as Actor>::Tell>>>,
    ) {
        tokio::spawn(async move {
            let mut ctx = ActorContext::<Self> {
                rx,
                extra_rxs: vec![],
                kill_flag: false,
            };

            loop {
                // Move any added extra channels to be polled that have been added in the loop
                if !ctx.extra_rxs.is_empty() {
                    extra_channel_receivers.append(&mut ctx.extra_rxs);
                }

                let mut remove_index: Option<usize> = None;
                //If we should poll multiple channels
                if !extra_channel_receivers.is_empty() {
                    let future = futures::future::select_all(
                        extra_channel_receivers
                            .iter_mut()
                            .map(|channel| channel.recv().boxed()),
                    );

                    tokio::select! {
                        msg = ctx.rx.recv() => {
                            //let mut ctx = lakka::ActorCtx::new(rx);
                            match msg {
                                Ok(msg) => self.handle_message(msg, &mut ctx).await,
                                Err(_) => {
                                    // The channel has closed, exit the loop
                                    break;
                                }
                            }
                        },
                        (result, index, _) = future => {

                            match result {
                                Ok(msg) => self.handle_tells(msg, &mut ctx).await,
                                Err(_) => remove_index = Some(index),
                            }
                        }
                    }
                    if let Some(index) = remove_index {
                        extra_channel_receivers.swap_remove(index);
                    }
                } else {
                    let msg = ctx.rx.recv().await;
                    match msg {
                        Ok(msg) => self.handle_message(msg, &mut ctx).await,
                        Err(_) => {
                            // The channel has closed, exit the loop
                            break;
                        }
                    }
                }

                if ctx.kill_flag {
                    break;
                }
            }
        });
    }
}

pub trait ActorMessage: Actor {
    type Message: Send;
}

impl<T: Actor> ActorMessage for T {
    type Message = Message<T::Ask, T::Tell>;
}

pub struct ActorContext<A>
where
    A: Actor,
{
    pub rx: Box<dyn Channel<Message<A::Ask, A::Tell>>>,
    pub extra_rxs: Vec<Box<dyn Channel<A::Tell>>>,
    pub kill_flag: bool,
}

impl<A: Actor + ActorMessage> ActorContext<A> {
    pub fn new(rx: Box<dyn Channel<Message<A::Ask, A::Tell>>>) -> Self {
        Self {
            rx,
            extra_rxs: vec![],
            kill_flag: false,
        }
    }

    pub fn shut_down_actor(&mut self) {
        self.kill_flag = true;
    }

    //* Takes Tell that will be processed, once */
    pub fn tell(&mut self, msg: A::Tell) {
        let msg = Singleshot::new(msg);
        self.extra_rxs.push(Box::new(msg));
    }

    pub fn delayed_tell(&mut self, msg: A::Tell, delay: std::time::Duration) {
        let msg = DelayedMessage {
            value: Some(msg),
            delay: Box::pin(tokio::time::sleep(delay)),
        };
        self.extra_rxs.push(Box::new(msg));
    }

    //* Adds extra channels that'll be used to receive Tells from */
    pub fn add_channel(&mut self, channel: Box<dyn Channel<A::Tell>>) {
        self.extra_rxs.push(channel);
    }
}

#[derive(Debug)]
pub enum ActorError {
    ActorClosed,
}

impl std::error::Error for ActorError {}

impl fmt::Display for ActorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ActorError::ActorClosed => write!(f, "Actor is closed"),
        }
    }
}

impl<T> From<SendError<T>> for ActorError {
    fn from(_: SendError<T>) -> Self {
        ActorError::ActorClosed
    }
}

impl From<RecvError> for ActorError {
    fn from(_: RecvError) -> Self {
        ActorError::ActorClosed
    }
}

pub trait ActorChannelSender<'a, T>: Send + Sync + fmt::Debug {
    type SendFuture: Future<Output = Result<(), ActorError>> + Send + 'a;
    fn send(&'a self, msg: T) -> Self::SendFuture;
    fn clone_box(&self) -> Box<dyn ActorChannelSender<'a, T, SendFuture = Self::SendFuture>>;
}

impl<'a, T: Send + 'static> ActorChannelSender<'a, T> for mpsc::Sender<T> {
    type SendFuture = Pin<Box<dyn Future<Output = Result<(), ActorError>> + Send + 'a>>;

    fn send(&'a self, msg: T) -> Self::SendFuture {
        Box::pin(async move { self.send(msg).await.map_err(|e| e.into()) })
    }

    fn clone_box(&self) -> Box<dyn ActorChannelSender<'a, T, SendFuture = Self::SendFuture>> {
        Box::new(self.clone())
    }
}

impl<'a, T: Send + 'static> ActorChannelSender<'a, T> for mpsc::UnboundedSender<T> {
    type SendFuture = Ready<Result<(), ActorError>>;

    fn send(&self, msg: T) -> Self::SendFuture {
        ready(self.send(msg).map_err(|e| e.into()))
    }

    fn clone_box(&self) -> Box<dyn ActorChannelSender<'a, T, SendFuture = Self::SendFuture>> {
        Box::new(self.clone())
    }
}

// Sending is non async, but also with no back pressure
pub trait UnboundedChannelSender<T>: fmt::Debug {
    fn send(&self, msg: T) -> Result<(), ActorError>;
    fn clone_box(&self) -> Box<dyn UnboundedChannelSender<T>>;
}
impl<T> Clone for Box<dyn UnboundedChannelSender<T>> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}
impl<T: Send + 'static> UnboundedChannelSender<T> for mpsc::UnboundedSender<T> {
    fn send(&self, msg: T) -> Result<(), ActorError> {
        self.send(msg).map_err(|e| e.into())
    }

    fn clone_box(&self) -> Box<dyn UnboundedChannelSender<T>> {
        Box::new(self.clone())
    }
}

///
/// ChannelSender trait for tokio::sync::mpsc::Sender<T> and such.
/// Maybe unnecessary, but wanted to experiment with alternative channels easily
///
pub trait ChannelSender<T>: Send + Sync + fmt::Debug {
    fn send(&self, msg: T) -> Pin<Box<dyn Future<Output = Result<(), ActorError>> + Send + '_>>;
    fn clone_box(&self) -> Box<dyn ChannelSender<T>>;
}

impl<T> Clone for Box<dyn ChannelSender<T>> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

impl<T: Send + 'static> ChannelSender<T> for mpsc::Sender<T> {
    fn send(&self, msg: T) -> Pin<Box<dyn Future<Output = Result<(), ActorError>> + Send + '_>> {
        //let sender = self.clone(); // Clone the sender
        Box::pin(async move { self.send(msg).await.map_err(|e| e.into()) })
    }

    fn clone_box(&self) -> Box<dyn ChannelSender<T>> {
        Box::new(self.clone())
    }
}

impl<T: Send + 'static> ChannelSender<T> for kanal::AsyncSender<T> {
    fn send(&self, msg: T) -> Pin<Box<dyn Future<Output = Result<(), ActorError>> + Send + '_>> {
        //let sender = self.clone(); // Clone the sender
        Box::pin(async move {
            match self.send(msg).await {
                Ok(_) => Ok(()),
                Err(_) => Err(ActorError::ActorClosed),
            }
        })
    }

    fn clone_box(&self) -> Box<dyn ChannelSender<T>> {
        Box::new(self.clone())
    }
}

///
/// Abstraction for channel receiver, so there can be many forms of receivers
///
pub trait Channel<T>: Send {
    fn recv(&mut self) -> Pin<Box<dyn Future<Output = Result<T, ActorError>> + Send + '_>>;
}

impl<T: Send> Channel<T> for mpsc::Receiver<T> {
    fn recv(&mut self) -> Pin<Box<dyn Future<Output = Result<T, ActorError>> + Send + '_>> {
        Box::pin(async move {
            match self.recv().await {
                Some(value) => Ok(value),
                None => Err(ActorError::ActorClosed),
            }
        })
    }
}

impl<T: Send> Channel<T> for mpsc::UnboundeReceiver<T> {
    fn recv(&mut self) -> Pin<Box<dyn Future<Output = Result<T, ActorError>> + Send + '_>> {
        Box::pin(async move {
            match self.recv().await {
                Some(value) => Ok(value),
                None => Err(ActorError::ActorClosed),
            }
        })
    }
}

impl<T: Send + Clone> Channel<T> for broadcast::Receiver<T> {
    fn recv(&mut self) -> Pin<Box<dyn Future<Output = Result<T, ActorError>> + Send + '_>> {
        Box::pin(async move {
            match broadcast::Receiver::recv(self).await {
                Ok(value) => Ok(value),
                Err(err) => match err {
                    tokio::sync::broadcast::error::RecvError::Closed => {
                        Err(ActorError::ActorClosed)
                    }
                    tokio::sync::broadcast::error::RecvError::Lagged(x) => {
                        eprint!("Lagged!: {}", x);
                        Err(ActorError::ActorClosed) //TODO: FIX
                    }
                },
            }
        })
    }
}

impl<T: Send> Channel<T> for kanal::AsyncReceiver<T> {
    fn recv(&mut self) -> Pin<Box<dyn Future<Output = Result<T, ActorError>> + Send + '_>> {
        Box::pin(async move {
            match kanal::AsyncReceiver::recv(self).await {
                Ok(value) => Ok(value),
                Err(_) => Err(ActorError::ActorClosed),
            }
        })
    }
}