ractor 0.15.12

A actor framework for Rust
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
// Copyright (c) Sean Lawlor
//
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree.

//! An implementation of the Chandy & Misra solution to the classic finite state machine (FSM)
//! concurrency problem known as [Dining Philosophers]
//! (https://en.wikipedia.org/wiki/Dining_philosophers_problem) problem using `ractor`.
//!
//! Utilizes:
//! * Multiple actors, inter-communicating
//! * RPCs
//! * Mutable state transitions
//!
//! Run this example with
//!
//! ```bash
//! cargo run --example philosophers
//! ```

#![allow(clippy::incompatible_msrv)]

use std::collections::HashMap;
use std::collections::VecDeque;

use ractor::cast;
use ractor::Actor;
use ractor::ActorId;
use ractor::ActorName;
use ractor::ActorProcessingErr;
use ractor::ActorRef;
use ractor::RpcReplyPort;
use tokio::time::Duration;
use tokio::time::Instant;

// ============================ Fork Actor ============================ //

enum ForkMessage {
    /// Request the fork be sent to a philosopher
    RequestFork(ActorRef<PhilosopherMessage>),
    /// Mark the fork as currently being used
    UsingFork(ActorId),
    /// Sent to a fork to indicate that it was put down and no longer is in use. This will
    /// allow the fork to be sent to the next user.
    PutForkDown(ActorId),
}
#[cfg(feature = "cluster")]
impl ractor::Message for ForkMessage {}

struct ForkState {
    /// Flag to identify if the fork is clean or not
    clean: bool,
    /// The actor who currently owns the fork
    owned_by: Option<ActorRef<PhilosopherMessage>>,
    // A backlog of messages which get queue'd up in a state transition
    backlog: VecDeque<ForkMessage>,
}

struct Fork;

impl Fork {
    fn handle_internal(
        &self,
        myself: &ActorRef<ForkMessage>,
        message: ForkMessage,
        state: &mut ForkState,
    ) -> Option<ForkMessage> {
        match &message {
            ForkMessage::RequestFork(who) => {
                match &state.owned_by {
                    Some(owner) => {
                        if !state.clean {
                            let _ = cast!(owner, PhilosopherMessage::GiveUpFork(myself.get_id()));
                        }
                        // there's already an owner, backlog this message in priority
                        return Some(message);
                    }
                    None => {
                        // give the fork to the requester
                        let _ = cast!(who, PhilosopherMessage::ReceiveFork(myself.get_id()));
                        // set ownership
                        state.owned_by = Some(who.clone());
                    }
                }
            }
            ForkMessage::UsingFork(who) => match &state.owned_by {
                Some(owner) if owner.get_id() == *who => {
                    state.clean = false;
                }
                Some(other_owner) => {
                    tracing::info!(
                        "ERROR Received `UsingFork` from {:?}. Real owner is {:?}",
                        who,
                        other_owner.get_name().unwrap()
                    );
                }
                None => {
                    tracing::info!("ERROR Received `UsingFork` from {who:?}. Real owner is `None`");
                }
            },
            ForkMessage::PutForkDown(who) => match &state.owned_by {
                Some(owner) if owner.get_id() == *who => {
                    state.owned_by = None;
                    state.clean = true;
                }
                Some(other_owner) => {
                    tracing::info!(
                        "ERROR Received `PutForkDown` from {:?}. Real owner is {:?}",
                        who,
                        other_owner.get_name().unwrap()
                    );
                }
                None => {
                    tracing::info!(
                        "ERROR Received `PutForkDown` from {who:?}. Real owner is `None`"
                    );
                }
            },
        }
        None
    }
}

#[cfg_attr(feature = "async-trait", ractor::async_trait)]
impl Actor for Fork {
    type Msg = ForkMessage;
    type State = ForkState;
    type Arguments = ();
    async fn pre_start(
        &self,
        _myself: ActorRef<Self::Msg>,
        _: (),
    ) -> Result<Self::State, ActorProcessingErr> {
        Ok(Self::State {
            clean: false,
            owned_by: None,
            backlog: VecDeque::new(),
        })
    }

    async fn handle(
        &self,
        myself: ActorRef<Self::Msg>,
        message: Self::Msg,
        state: &mut Self::State,
    ) -> Result<(), ActorProcessingErr> {
        let mut maybe_unhandled = self.handle_internal(&myself, message, state);
        if let Some(message) = maybe_unhandled {
            state.backlog.push_back(message);
        } else {
            // we handled the message, check the queue for any work to dequeue and handle
            while !state.backlog.is_empty() && maybe_unhandled.is_none() {
                let head = state.backlog.pop_front().unwrap();
                maybe_unhandled = self.handle_internal(&myself, head, state);
            }
            // put the first unhandled msg back to the front of the queue
            if let Some(msg) = maybe_unhandled {
                state.backlog.push_front(msg);
            }
        }
        Ok(())
    }
}

// ============================ Philosopher Actor ============================ //

#[derive(PartialEq, Eq)]
enum PhilosopherMode {
    /// The philosopher is thinking
    Thinking,
    /// The philosopher is hungry and waiting for one of the forks
    Hungry,
    /// The philosopher is eating
    Eating,
}

struct PhilosophersFork {
    /// The pointer to the fork actor
    fork: ActorRef<ForkMessage>,
    /// Does this philosopher currently have this fork?
    has: bool,
    /// Has the philosopher requested this fork?
    requested: bool,
}

#[derive(Clone, Debug)]
struct PhilosopherMetrics {
    /// The number of state changes that have occurred.
    state_change_count: u16,
    /// The number of times a Philosopher failed to eat because he didn't have both forks.
    failed_to_eat: u16,
    /// The time that the Philosopher spent thinking.
    time_thinking: Duration,
    /// The time that the Philosopher spent hungry.
    time_hungry: Duration,
    /// The time that the Philosopher spent eating.
    time_eating: Duration,
}

struct PhilosopherState {
    /// The current mode/state the philosopher is in
    mode: PhilosopherMode,
    /// The fork to the left of the Philosopher
    left: PhilosophersFork,
    /// The fork to the right of the Philosopher
    right: PhilosophersFork,
    /// The last time the philosopher's state changed. Tracking time eating, etc
    last_state_change: Instant,
    /// The metrics of this actor
    metrics: PhilosopherMetrics,
    /// time-slice
    time_slice: Duration,
}

impl PhilosopherState {
    fn new(
        left: ActorRef<ForkMessage>,
        right: ActorRef<ForkMessage>,
        time_slice: Duration,
    ) -> Self {
        Self {
            mode: PhilosopherMode::Thinking,
            left: PhilosophersFork {
                fork: left,
                has: false,
                requested: false,
            },
            right: PhilosophersFork {
                fork: right,
                has: false,
                requested: false,
            },
            last_state_change: Instant::now(),
            metrics: PhilosopherMetrics {
                state_change_count: 0,
                failed_to_eat: 0,
                time_thinking: Duration::from_micros(0),
                time_hungry: Duration::from_micros(0),
                time_eating: Duration::from_micros(0),
            },
            time_slice,
        }
    }
}

enum PhilosopherMessage {
    /// Command to stop eating. Note that since the `StopEating` message is sent as a scheduled message
    /// it may arrive after the philosopher has already changed state. For this reason we track
    /// the state change count and compare it with the number in the message.
    StopEating(u16),
    /// Command to stop eating. Note that since the `BecomeHungry` message is sent as a scheduled message
    /// it may arrive after the philosopher has already changed state. For this reason we track
    /// the state change count and compare it with the number in the message.
    BecomeHungry(u16),
    /// Instructs the philosopher to give up the fork
    GiveUpFork(ActorId),
    /// Instructs the philosopher they've received the specified fork
    ReceiveFork(ActorId),
    SendMetrics(RpcReplyPort<PhilosopherMetrics>),
}
#[cfg(feature = "cluster")]
impl ractor::Message for PhilosopherMessage {}

struct PhilosopherArguments {
    time_slice: Duration,
    left: ActorRef<ForkMessage>,
    right: ActorRef<ForkMessage>,
}

struct Philosopher;

impl Philosopher {
    /// Helper method to set the internal state to begin thinking
    fn begin_thinking(&self, myself: &ActorRef<PhilosopherMessage>, state: &mut PhilosopherState) {
        state.mode = PhilosopherMode::Thinking;
        state.metrics.state_change_count += 1;
        state.metrics.time_eating += Instant::elapsed(&state.last_state_change);
        state.last_state_change = Instant::now();

        // schedule become hungry after the thinking time has elapsed
        let metrics_count = state.metrics.state_change_count;
        #[allow(clippy::let_underscore_future)]
        let _ = myself.send_after(state.time_slice, move || {
            PhilosopherMessage::BecomeHungry(metrics_count)
        });
    }

    /// Helper command to set the internal state to begin eating
    fn begin_eating(&self, myself: &ActorRef<PhilosopherMessage>, state: &mut PhilosopherState) {
        state.metrics.time_hungry += Instant::elapsed(&state.last_state_change);
        state.last_state_change = Instant::now();
        state.mode = PhilosopherMode::Eating;
        state.metrics.state_change_count += 1;

        // Now that we are eating we will tell the fork that we are using it,
        // thus marking the fork as dirty.
        let _ = state
            .left
            .fork
            .cast(ForkMessage::UsingFork(myself.get_id()));
        let _ = state
            .right
            .fork
            .cast(ForkMessage::UsingFork(myself.get_id()));

        // schedule stop eating after the eating time has elapsed
        let metrics_count = state.metrics.state_change_count;
        #[allow(clippy::let_underscore_future)]
        let _ = myself.send_after(state.time_slice, move || {
            PhilosopherMessage::StopEating(metrics_count)
        });
    }

    /// Helper command to request any forks which are missing
    fn request_missing_forks(
        &self,
        myself: &ActorRef<PhilosopherMessage>,
        state: &mut PhilosopherState,
    ) {
        if !state.left.has && !state.left.requested {
            state.left.requested = true;
            let _ = state
                .left
                .fork
                .cast(ForkMessage::RequestFork(myself.clone()));
        }
        if !state.right.has && !state.right.requested {
            state.right.requested = true;
            let _ = state
                .right
                .fork
                .cast(ForkMessage::RequestFork(myself.clone()));
        }
    }
}

#[cfg_attr(feature = "async-trait", ractor::async_trait)]
impl Actor for Philosopher {
    type Msg = PhilosopherMessage;
    type State = PhilosopherState;
    type Arguments = PhilosopherArguments;
    async fn pre_start(
        &self,
        myself: ActorRef<Self::Msg>,
        args: PhilosopherArguments,
    ) -> Result<Self::State, ActorProcessingErr> {
        // initialize the simulation by making the philosopher's hungry
        let _ = cast!(myself, Self::Msg::BecomeHungry(0));
        Ok(Self::State::new(args.left, args.right, args.time_slice))
    }

    async fn handle(
        &self,
        myself: ActorRef<Self::Msg>,
        message: Self::Msg,
        state: &mut Self::State,
    ) -> Result<(), ActorProcessingErr> {
        match message {
            PhilosopherMessage::SendMetrics(reply) => {
                let _ = reply.send(state.metrics.clone());
            }
            PhilosopherMessage::StopEating(state_id) => {
                // Processes a command to stop eating.
                if state.metrics.state_change_count == state_id
                    && state.mode == PhilosopherMode::Eating
                {
                    self.begin_thinking(&myself, state);
                }
            }
            PhilosopherMessage::BecomeHungry(state_id) => {
                // The philosopher is being instructed to get hungry which will cause them to ask for the
                // forks to eat.
                if state.metrics.state_change_count == state_id {
                    if state.left.has && state.right.has {
                        // we have both forks, starting eating
                        self.begin_eating(&myself, state);
                    } else {
                        // we're missing some forks, maybe request the forks we need?
                        match state.mode {
                            PhilosopherMode::Thinking => {
                                state.metrics.time_thinking +=
                                    Instant::elapsed(&state.last_state_change);
                                state.last_state_change = Instant::now();
                                state.mode = PhilosopherMode::Hungry;
                                state.metrics.state_change_count += 1;
                                self.request_missing_forks(&myself, state);
                            }
                            PhilosopherMode::Hungry => {
                                tracing::info!(
                                    "ERROR: {} Got `BecomeHungry` while hungry!",
                                    myself.get_name().unwrap()
                                );
                            }
                            PhilosopherMode::Eating => {
                                tracing::info!(
                                    "ERROR: {} Got `BecomeHungry` while eating!",
                                    myself.get_name().unwrap()
                                );
                            }
                        }
                    }
                }
            }
            PhilosopherMessage::GiveUpFork(fork) => {
                // Processes a command to a philosopher to give up a fork. Note that this can be received
                // when the philosopher is in any state since the philosopher will not put down a fork
                // unless he is asked to. A philosopher can be eating, stop eating and start thinking
                // and then start eating again if no one asked for his forks. The fork actor is the only
                // actor sending this message and it will only do so if the fork is dirty.
                if state.left.fork.get_id() == fork {
                    if state.left.has {
                        state.left.has = false;
                        let _ = state
                            .left
                            .fork
                            .cast(ForkMessage::PutForkDown(myself.get_id()));
                    }
                } else if state.right.fork.get_id() == fork {
                    if state.right.has {
                        state.right.has = false;
                        let _ = state
                            .right
                            .fork
                            .cast(ForkMessage::PutForkDown(myself.get_id()));
                    }
                } else {
                    tracing::info!(
                        "ERROR: {} received a `GiveUpFork` from an unknown fork!",
                        myself.get_name().unwrap()
                    );
                }
                match state.mode {
                    PhilosopherMode::Hungry => {
                        state.metrics.failed_to_eat += 1;
                        self.begin_thinking(&myself, state);
                    }
                    PhilosopherMode::Eating => {
                        self.begin_thinking(&myself, state);
                    }
                    _ => {
                        // already thinking
                    }
                }
            }
            PhilosopherMessage::ReceiveFork(fork) => {
                // The philosopher received a fork. Once they have both forks they can start eating.
                // Otherwise they have to wait for the other fork to begin eating.
                if state.left.fork.get_id() == fork {
                    state.left.has = true;
                    state.left.requested = false;
                } else if state.right.fork.get_id() == fork {
                    state.right.has = true;
                    state.right.requested = false;
                } else {
                    tracing::info!(
                        "ERROR: {} received a `ReceiveFork` from an unknown fork!",
                        myself.get_name().unwrap()
                    );
                }

                // if we have both forks, we can start eating
                if state.left.has && state.right.has {
                    self.begin_eating(&myself, state);
                }
            }
        }
        Ok(())
    }
}

fn init_logging() {
    let dir = tracing_subscriber::filter::Directive::from(tracing::Level::DEBUG);

    use std::io::stderr;
    use std::io::IsTerminal;

    use tracing_glog::Glog;
    use tracing_glog::GlogFields;
    use tracing_subscriber::filter::EnvFilter;
    use tracing_subscriber::layer::SubscriberExt;
    use tracing_subscriber::Registry;

    let fmt = tracing_subscriber::fmt::Layer::default()
        .with_ansi(stderr().is_terminal())
        .with_writer(std::io::stderr)
        .event_format(Glog::default().with_timer(tracing_glog::LocalTime::default()))
        .fmt_fields(GlogFields::default().compact());

    let filter = vec![dir]
        .into_iter()
        .fold(EnvFilter::from_default_env(), |filter, directive| {
            filter.add_directive(directive)
        });

    let subscriber = Registry::default().with(filter).with(fmt);
    tracing::subscriber::set_global_default(subscriber).expect("to set global subscriber");
}

#[ractor_example_entry_proc::ractor_example_entry]
async fn main() {
    init_logging();

    // TODO: move configuration to CLAP args
    let time_slice = Duration::from_millis(10);
    let run_time = Duration::from_secs(5);

    let philosopher_names = [
        "Confucius",
        "Descartes",
        "Benjamin Franklin",
        "Socrates",
        "Aristotle",
        "Plato",
        "John Locke",
        "Nietzsche",
        "Karl Marx",
        "Pythagoras",
        "Montesquieu",
    ];
    let mut forks = Vec::with_capacity(philosopher_names.len());
    let mut philosophers = Vec::with_capacity(philosopher_names.len());
    let mut all_handles = tokio::task::JoinSet::new();

    let mut results: HashMap<ActorName, Option<PhilosopherMetrics>> =
        HashMap::with_capacity(philosopher_names.len());

    // create the forks
    for _i in 0..philosopher_names.len() {
        let (fork, handle) = Actor::spawn(None, Fork, ())
            .await
            .expect("Failed to create fork!");
        forks.push(fork);
        all_handles.spawn(handle);
    }

    // Spawn the philosopher actors clockwise from top of the table
    for left in 0..philosopher_names.len() {
        let right = if left == 0 {
            philosopher_names.len() - 1
        } else {
            left - 1
        };
        let p = PhilosopherArguments {
            time_slice,
            left: forks[left].clone(),
            right: forks[right].clone(),
        };
        let (philosopher, handle) =
            Actor::spawn(Some(philosopher_names[left].to_string()), Philosopher, p)
                .await
                .expect("Failed to create philosopher!");
        results.insert(philosopher_names[left].to_string(), None);
        philosophers.push(philosopher);
        all_handles.spawn(handle);
    }

    // wait for the simulation to end
    tokio::time::sleep(run_time).await;
    // collect the metrics from the philosophers, and they'll stop after reporting metrics
    for philosopher in philosophers.iter() {
        let metrics = ractor::call_t!(philosopher, PhilosopherMessage::SendMetrics, 50)
            .expect("Failed to perform RPC");
        results.insert(philosopher.get_name().unwrap(), Some(metrics));
    }

    // cleanup forks & philosophers
    for fork in forks {
        fork.stop(None);
    }
    for philosopher in philosophers {
        philosopher.stop(None);
    }

    // wait for everything to shut down
    while all_handles.join_next().await.is_some() {}

    // print metrics
    tracing::info!("Simulation results");
    for (who, metric) in results {
        tracing::info!("{who}: {metric:?}");
    }
}