tokactor 2.1.0

A actor model framework wrapped around tokio
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use std::time::Duration;

use tokio::sync::{mpsc, watch};

use crate::{
    context::{ActorState, SupervisorMessage},
    envelope::SendMessage,
    message::DeadActor,
    single::{AskRx, AsyncAskRx},
    Actor, ActorRef, Ask, AskResult, AsyncAsk, Ctx, Handler, Message, Scheduler, SendError,
};

pub(crate) enum ExecutorLoop {
    Continue,
    Break,
}

type SupervisorReciever = watch::Receiver<Option<SupervisorMessage>>;

pub(crate) struct RawExecutor<A: Actor>(Option<Executor<A>>);

impl<A: Actor> RawExecutor<A> {
    pub fn raw_start(&mut self) {
        if let Some(executor) = self.0.as_mut() {
            executor.actor.on_start(&mut executor.context);
        } else {
            unreachable!()
        }
    }

    // pub async fn recv(&mut self) -> Option<Box<dyn SendMessage<A>>> {
    //     if let Some(executor) = self.0.as_mut() {
    //         executor.context.mailbox.recv().await
    //     } else {
    //         unreachable!()
    //     }
    // }

    // pub async fn process(&mut self, message: Option<Box<dyn SendMessage<A>>>) -> ExecutorLoop {
    //     if let Some(message) = message {
    //         let executor: Executor<A> = self.0.take().unwrap();
    //         // this process_message is not safe
    //         let (executor, event) = executor.process_message(message).await;
    //         self.0 = Some(executor);
    //         event
    //     } else {
    //         ExecutorLoop::Break
    //     }
    // }

    // pub async fn receive_messages(&mut self) -> ExecutorLoop {
    //     let mut executor: Executor<A> = self.0.take().unwrap();

    //     executor.check_anonymous_actors().await;

    //     while let Ok(message) = executor.context.mailbox.try_recv() {
    //         let (this, event) = executor.process_message(message).await;
    //         executor = this;
    //         if matches!(event, ExecutorLoop::Break) {
    //             self.0 = Some(executor);
    //             return ExecutorLoop::Break;
    //         }
    //     }

    //     self.0 = Some(executor);
    //     ExecutorLoop::Continue
    // }

    pub async fn raw_shutdown(mut self) {
        let executor = self.0.take().unwrap();

        let mut this = executor.shutdown().await;
        if let Some(tx) = this.context.into_future_sender.take() {
            let _ = tx.into_inner().send(this.actor);
        }
    }

    // TODO(Alec): Remove
    // pub fn handle<M>(&mut self, message: M)
    // where
    //     M: Message,
    //     A: Handler<M>,
    // {
    //     if let Some(executor) = self.0.as_mut() {
    //         executor.actor.handle(message, &mut executor.context)
    //     } else {
    //         unreachable!()
    //     }
    // }

    pub fn ask<M>(&mut self, message: M) -> <A as Ask<M>>::Result
    where
        M: Message,
        A: Ask<M>,
    {
        if let Some(executor) = self.0.as_mut() {
            match executor.actor.handle(message, &mut executor.context) {
                AskResult::Reply(reply) => reply,
                AskResult::Task(_) => unreachable!(), // TODO(Alec): need to fix this
            }
        } else {
            unreachable!()
        }
    }

    // TODO(Alec): Remove
    // pub fn spawn<Child>(&mut self, child: Child) -> ActorRef<Child>
    // where
    //     A: Handler<DeadActorResult<Child>>,
    //     Child: Actor,
    // {
    //     if let Some(executor) = self.0.as_mut() {
    //         executor.context.spawn(child)
    //     } else {
    //         unreachable!()
    //     }
    // }

    pub fn with_ctx<Out, F: FnOnce(&Ctx<A>) -> Out>(&self, f: F) -> Out {
        if let Some(executor) = self.0.as_ref() {
            f(&executor.context)
        } else {
            unreachable!()
        }
    }
}

pub(crate) struct Executor<A: Actor> {
    pub actor: A,
    pub context: Ctx<A>,
    pub receiver: Option<SupervisorReciever>,
}

impl<A: Actor> Executor<A> {
    pub fn into_raw(self) -> RawExecutor<A> {
        RawExecutor(Some(self))
    }

    pub fn new(actor: A, context: Ctx<A>) -> Self {
        Self {
            actor,
            context,
            receiver: None,
        }
    }

    pub fn child(actor: A, context: Ctx<A>, receiver: SupervisorReciever) -> Self {
        Self {
            actor,
            context,
            receiver: Some(receiver),
        }
    }

    pub fn into_dead_actor(mut self) -> (Option<SupervisorReciever>, DeadActor<A>) {
        (
            self.receiver.take(),
            DeadActor {
                actor: self.actor,
                ctx: self.context,
            },
        )
    }

    /// Check to see if the we are executing more anonymous actors then initally
    /// allowed to run. If we are, then wait for some anonymous tasks to complete
    /// before continuing to execute the parent actor
    async fn check_anonymous_actors(&mut self) {
        let avaliable_permits = self.context.max_anonymous_actors.available_permits();
        let overflow = self.context.overflow_anonymous_actors;
        if avaliable_permits == 0 && overflow > 0 {
            if overflow < A::max_anonymous_actors() {
                let _ = self
                    .context
                    .max_anonymous_actors
                    .acquire_many(overflow as u32)
                    .await;
                self.context.overflow_anonymous_actors = 0;
            } else {
                // TODO(Alec): The user has spawned more anonymous actors then we
                //             can relistically track...
                let _ = self
                    .context
                    .max_anonymous_actors
                    .acquire_many(A::max_anonymous_actors() as u32)
                    .await;
                self.context.overflow_anonymous_actors -= A::max_anonymous_actors();
            }
        } else if overflow > 0 {
            let running_tasks = A::max_anonymous_actors() - avaliable_permits;
            if overflow < running_tasks {
                let _ = self
                    .context
                    .max_anonymous_actors
                    .acquire_many(overflow as u32)
                    .await;
                self.context.overflow_anonymous_actors = 0;
            } else {
                // TODO(Alec): The amount of overflow tasks is more then the avaliable
                //             running tasks...
                let _ = self
                    .context
                    .max_anonymous_actors
                    .acquire_many(running_tasks as u32)
                    .await;
                self.context.overflow_anonymous_actors -= running_tasks;
            }
        }
    }

    /// Run an actor that accepts messages from it's supervisor as well as from
    /// it's mailbox. Continue processing messages until told other wise.
    pub async fn run_supervised_actor(mut self) -> Self {
        tracing::trace!(
            callback = "on_start",
            actor = A::name(),
            lifecycle = self.context.state.to_string()
        );
        self.actor.on_start(&mut self.context);
        loop {
            self.check_anonymous_actors().await;
            let (this, event) = self.handle_supervised_message().await;
            self = this;
            match event {
                ExecutorLoop::Continue => {}
                ExecutorLoop::Break => break,
            }
        }
        self.shutdown().await
    }

    /// Run an actor but only accept messages from a mailbox. This actor has no
    /// supervisor so it can not recieve messages from one. Continue to accept
    /// messges until the mailbox is closed.
    pub async fn run_actor(mut self) {
        self.actor.on_start(&mut self.context);
        while let Some(msg) = self.context.mailbox.recv().await {
            self.check_anonymous_actors().await;
            let (this, event) = self.process_message(msg).await;
            self = this;
            match event {
                ExecutorLoop::Continue => {}
                ExecutorLoop::Break => break,
            }
        }
        let mut this = self.shutdown().await;
        if let Some(tx) = this.context.into_future_sender.take() {
            let _ = tx.into_inner().send(this.actor);
        }
    }

    /// Wait for one of the following events
    ///
    /// 1. A item is recieved in our mailbox
    /// 2. We recieve a priority event from our supervisor
    ///
    /// Process the event that is recieved first. The message from the supervisor
    /// takes president if both recieve a message at the same time.
    ///
    /// Decide whether if the executor loop should continue to execute.
    async fn handle_supervised_message(mut self) -> (Self, ExecutorLoop) {
        assert!(self.receiver.is_some());
        let reciever = self.receiver.as_mut().unwrap();
        let result = tokio::select! {
            // Or recieve a message from our supervisor
            result = reciever.changed() => match result {
                Ok(_) => match *reciever.borrow() {
                    Some(SupervisorMessage::Shutdown) => {
                        tracing::trace!(
                            actor = A::name(),
                            lifecycle = self.context.state.to_string(),
                            "Recieved shutdown message"
                        );
                        ExecutorLoop::Break
                    },
                    None => ExecutorLoop::Continue,
                },
                Err(err) => {
                    panic!("Supervisor died before child. This shouldn't happen: {:?}", err)
                }
            },
            // attempt to run actor to completion
            option = self.context.mailbox.recv() => {
                if let Some(message) = option {
                    return self.process_message(message).await
                } else {
                    ExecutorLoop::Break
                }
            }
        };
        (self, result)
    }

    /// Process a single message from an actors mailbox. Depending on the state of
    /// the actor, return whether the actor should continue running.
    async fn process_message(
        mut self,
        mut message: Box<dyn SendMessage<A>>,
    ) -> (Self, ExecutorLoop) {
        tracing::trace!(
            callback = "pre_run",
            actor = A::name(),
            lifecycle = self.context.state.to_string()
        );
        self.actor.pre_run(&mut self.context);
        match message.scheduler() {
            Scheduler::Blocking => {
                // TODO(Alec): Should we panic here? I think we should as it would
                // propagate the panic up the stack. It is advaised that you should
                // not ever panic in an actor if it's in your control.
                self = tokio::task::spawn_blocking(move || {
                    tracing::debug!(
                        callback = "recv",
                        actor = A::name(),
                        message = std::any::type_name::<dyn SendMessage<A>>(),
                        lifecycle = self.context.state.to_string(),
                        schedule = "blocking",
                        "recieved blocking message"
                    );
                    message.send(&mut self.actor, &mut self.context);
                    self
                })
                .await
                .unwrap();
            }
            Scheduler::NonBlocking => {
                tracing::debug!(
                    callback = "recv",
                    actor = A::name(),
                    message = std::any::type_name::<dyn SendMessage<A>>(),
                    lifecycle = self.context.state.to_string(),
                    schedule = "non-blocking",
                    "recieved message"
                );
                message.send(&mut self.actor, &mut self.context).await;
            }
        }
        tracing::trace!(
            callback = "post_run",
            actor = A::name(),
            lifecycle = self.context.state.to_string()
        );
        self.actor.post_run(&mut self.context);

        if matches!(self.context.state, ActorState::Running) {
            (self, ExecutorLoop::Continue)
        } else {
            (self, ExecutorLoop::Break)
        }
    }

    /// Shutdown the actor by sending a message to all children to kill themselves
    /// and then wait until we have no more children left and all of our messages
    /// have been processed.
    async fn shutdown(mut self) -> Self {
        self.context.state = ActorState::Stopping;
        tracing::trace!(
            callback = "on_stopping",
            actor = A::name(),
            lifecycle = self.context.state.to_string()
        );
        self.actor.on_stopping(&mut self.context);
        self = self.stopping().await;
        self.context.state = ActorState::Stopped;
        tracing::trace!(
            callback = "on_stopped",
            actor = A::name(),
            lifecycle = self.context.state.to_string()
        );
        self.actor.on_stopped(&mut self.context);
        self = self.stop().await;
        tracing::trace!(
            callback = "on_end",
            actor = A::name(),
            lifecycle = self.context.state.to_string()
        );
        self.actor.on_end(&mut self.context);
        self
    }

    /// Called when the actors mailbox should be closed. Transition the actor
    /// into a stopping state.
    async fn stopping(mut self) -> Self {
        // We have no children, so we can just move to the stopping state. If we had
        // children, then we want to continue running and recieving messages until
        // all of our children have died.
        if self.context.notifier.is_closed() {
            // TODO(Alec): Should this be configurable. A lot of examples of other
            //             actor libraries allow for an actor to continue sending
            //             messages to itself. We could support this if we could
            //             close the mailbox only when all messages have been recieved.
            //             This would mean an actor could continue sending messages
            //             to itself until it's completed some type of test.
            //             Example of what I'm talking about: https://github.com/slawlor/ractor/blob/main/ractor/benches/actor.rs

            // We have no children. Go to ending state.
            self.context.mailbox.close();
            return self;
        }

        let _ = self
            .context
            .notifier
            .send(Some(SupervisorMessage::Shutdown));

        let mut timeout_counter = 0;
        loop {
            tokio::select! {
                option = self.context.mailbox.recv() => {
                    if let Some(msg) = option {
                        let (this, _) = self.process_message(msg).await;
                        self = this;
                    }
                }
                _ = tokio::time::sleep(Duration::from_secs(1)) => {
                    tracing::warn!(
                        actor = A::name(),
                        lifecycle = self.context.state.to_string(),
                        counter = timeout_counter,
                        time = "1sec",
                        "Pausing to allow for actors to exit"
                    );
                    if timeout_counter == 10 {
                        panic!("Timeout counter reached 10. Not all actors are exiting when they should be");
                    }
                    timeout_counter += 1;
                }
            }

            // If all of our children have died
            if self.context.notifier.is_closed() {
                self.context.mailbox.close();
                return self;
            }
        }
    }

    /// Call only when all children are dead and the actor is no longer supervising
    /// any more children. Completely empty the remaining items in the mailbox.
    async fn stop(mut self) -> Self {
        assert!(self.context.notifier.is_closed());
        while let Ok(msg) = self.context.mailbox.try_recv() {
            let (this, _) = self.process_message(msg).await;
            self = this;
        }
        self
    }
}

impl<A: Actor> Executor<A> {
    pub(crate) async fn child_with_custom_handle_rx<Parent, In>(
        mut self,
        parent: ActorRef<Parent>,
        mut rx: mpsc::Receiver<In>,
    ) where
        Parent: Actor + Handler<In>,
        In: Message,
    {
        self.actor.on_start(&mut self.context);

        loop {
            let reciever = self.receiver.as_mut().unwrap();

            let event = tokio::select! {
                // Or recieve a message from our supervisor
                result = reciever.changed() => match result {
                    Ok(_) => match *reciever.borrow() {
                        Some(SupervisorMessage::Shutdown) => ExecutorLoop::Break,
                        None => ExecutorLoop::Continue,
                    },
                    Err(err) => {
                        panic!("Supervisor died before child. This shouldn't happen: {:?}", err)
                    }
                },
                // attempt to run actor to completion
                option = rx.recv() => {
                    if let Some(message) = option {
                        if let Err(err) = parent.send_async(message).await {
                            match err {
                                SendError::Closed(_) => ExecutorLoop::Break,
                                SendError::Full(_) => ExecutorLoop::Continue,
                                SendError::Lost => ExecutorLoop::Continue,
                            }
                        } else {
                            ExecutorLoop::Continue
                        }
                    } else {
                        ExecutorLoop::Break
                    }
                }
            };

            match event {
                ExecutorLoop::Continue => {}
                ExecutorLoop::Break => break,
            }
        }

        self.shutdown().await;
    }

    pub(crate) async fn child_with_custom_ask_rx<Parent, In>(
        mut self,
        parent: ActorRef<Parent>,
        mut rx: AskRx<In, Parent>,
    ) where
        Parent: Actor + Ask<In>,
        In: Message,
    {
        self.actor.on_start(&mut self.context);

        loop {
            let reciever = self.receiver.as_mut().unwrap();

            let event = tokio::select! {
                // Or recieve a message from our supervisor
                result = reciever.changed() => match result {
                    Ok(_) => match *reciever.borrow() {
                        Some(SupervisorMessage::Shutdown) => ExecutorLoop::Break,
                        None => ExecutorLoop::Continue,
                    },
                    Err(err) => {
                        panic!("Supervisor died before child. This shouldn't happen: {:?}", err)
                    }
                },
                // attempt to run actor to completion
                option = rx.recv() => {
                    if let Some((message, rx)) = option {
                        let _ = rx.send(parent.ask(message).await);
                        ExecutorLoop::Continue
                    } else {
                        ExecutorLoop::Break
                    }
                }
            };

            match event {
                ExecutorLoop::Continue => {}
                ExecutorLoop::Break => break,
            }
        }

        self.shutdown().await;
    }

    pub(crate) async fn child_with_custom_async_ask_rx<Parent, In>(
        mut self,
        parent: ActorRef<Parent>,
        mut rx: AsyncAskRx<In, Parent>,
    ) where
        Parent: Actor + AsyncAsk<In>,
        In: Message,
    {
        self.actor.on_start(&mut self.context);

        loop {
            let reciever = self.receiver.as_mut().unwrap();

            let event = tokio::select! {
                // Or recieve a message from our supervisor
                result = reciever.changed() => match result {
                    Ok(_) => match *reciever.borrow() {
                        Some(SupervisorMessage::Shutdown) => ExecutorLoop::Break,
                        None => ExecutorLoop::Continue,
                    },
                    Err(err) => {
                        panic!("Supervisor died before child. This shouldn't happen: {:?}", err)
                    }
                },
                // attempt to run actor to completion
                option = rx.recv() => {
                    if let Some((message, rx)) = option {
                        let _ = rx.send(parent.async_ask(message).await);
                        ExecutorLoop::Continue
                    } else {
                        ExecutorLoop::Break
                    }
                }
            };

            match event {
                ExecutorLoop::Continue => {}
                ExecutorLoop::Break => break,
            }
        }

        self.shutdown().await;
    }
}