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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// 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.

//! Process groups (PG) are named groups of actors with a friendly name
//! which can be used for retrieval of the process groups. Then within
//! the group, either a random actor (for dispatch) can be selected or
//! the whole group (broadcast), or a subset (partial-broadcast) can have
//! a message sent to them. Common operations are to (a) upcast the group
//! members to a strong-type'd actor then dispatch a message with [crate::call]
//! or [crate::cast].
//!
//! Process groups can also be monitored for changes with calling [monitor] to
//! subscribe to changes and [demonitor] to unsubscribe. Subscribers will receive
//! process group change notifications via a [SupervisionEvent] called on the
//! supervision port of the [crate::Actor]
//!
//! Inspired from [Erlang's `pg` module](https://www.erlang.org/doc/man/pg.html)
//!
//! ## Examples
//!
//! ```rust
//! use ractor::pg;
//! use ractor::Actor;
//! use ractor::ActorProcessingErr;
//! use ractor::ActorRef;
//!
//! struct ExampleActor;
//!
//! #[cfg_attr(feature = "async-trait", ractor::async_trait)]
//! impl Actor for ExampleActor {
//!     type Msg = ();
//!     type State = ();
//!     type Arguments = ();
//!
//!     async fn pre_start(
//!         &self,
//!         _myself: ActorRef<Self::Msg>,
//!         _args: Self::Arguments,
//!     ) -> Result<Self::State, ActorProcessingErr> {
//!         println!("Starting");
//!         Ok(())
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let (actor, handle) = Actor::spawn(None, ExampleActor, ())
//!         .await
//!         .expect("Failed to startup dummy actor");
//!     let group = "the_group".to_string();
//!
//!     // Join the actor to a group. This is also commonly done in `pre_start` or `post_start`
//!     // of the actor itself without having to do it externally by some coordinator
//!     pg::join(group.clone(), vec![actor.get_cell()]);
//!     // Retrieve the pg group membership
//!     let members = pg::get_members(&group);
//!     // Send a message to the up-casted actor
//!     let the_actor: ActorRef<()> = members.get(0).unwrap().clone().into();
//!     ractor::cast!(the_actor, ()).expect("Failed to send message");
//!
//!     // wait for actor exit
//!     actor.stop(None);
//!     handle.await.unwrap();
//!
//!     // The actor will automatically be removed from the group upon shutdown.
//!     let members = pg::get_members(&group);
//!     assert_eq!(members.len(), 0);
//! }
//! ```

use std::collections::HashMap;
use std::collections::HashSet;

use dashmap::mapref::entry::Entry::Occupied;
use dashmap::DashMap;
use once_cell::sync::OnceCell;

use crate::ActorCell;
use crate::ActorId;
use crate::ActorStatus;
use crate::GroupName;
use crate::ScopeName;
use crate::SupervisionEvent;

/// Key to set the default scope
pub const DEFAULT_SCOPE: &str = "__default_scope__";

/// Key to monitor all of the scopes
pub const ALL_SCOPES_NOTIFICATION: &str = "__world_scope__";

/// Key to monitor all of the groups in a scope
pub const ALL_GROUPS_NOTIFICATION: &str = "__world_group_";

#[cfg(test)]
mod tests;

/// Represents a change in a process group's membership
#[derive(Clone, Debug)]
pub enum GroupChangeMessage {
    /// Some actors joined a group
    Join(ScopeName, GroupName, Vec<ActorCell>),
    /// Some actors left a group
    Leave(ScopeName, GroupName, Vec<ActorCell>),
}

impl GroupChangeMessage {
    /// Retrieve the group that changed
    pub fn get_group(&self) -> GroupName {
        match self {
            Self::Join(_, name, _) => name.clone(),
            Self::Leave(_, name, _) => name.clone(),
        }
    }

    /// Retrieve the name of the scope in which the group change took place
    pub fn get_scope(&self) -> ScopeName {
        match self {
            Self::Join(scope, _, _) => scope.to_string(),
            Self::Leave(scope, _, _) => scope.to_string(),
        }
    }
}

/// Represents the combination of a `ScopeName` and a `GroupName`
/// that uniquely identifies a specific group in a specific scope
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ScopeGroupKey {
    /// the `ScopeName`
    scope: ScopeName,
    /// The `GroupName`
    group: GroupName,
}

impl ScopeGroupKey {
    /// Retrieve the struct's scope
    pub fn get_scope(&self) -> ScopeName {
        self.scope.to_owned()
    }
    /// Retrieve the struct's group
    pub fn get_group(&self) -> GroupName {
        self.group.to_owned()
    }
}

/// Internal state for a single process group, bundling members and per-group
/// listeners into a single atomically-accessible unit.
#[derive(Default)]
struct GroupState {
    /// The actors that are members of this group
    members: HashMap<ActorId, ActorCell>,
    /// Actors monitoring this specific group for changes
    listeners: Vec<ActorCell>,
}

struct PgState {
    /// Maps (scope, group) to the group's state (members + per-group listeners)
    map: DashMap<ScopeGroupKey, GroupState>,
    /// Secondary index: scope -> set of group names that have members
    index: DashMap<ScopeName, HashSet<GroupName>>,
    /// Scope-level and global monitors (sentinel keys only)
    world_listeners: DashMap<ScopeGroupKey, Vec<ActorCell>>,
}

static PG_MONITOR: OnceCell<PgState> = OnceCell::new();

fn get_monitor<'a>() -> &'a PgState {
    PG_MONITOR.get_or_init(|| PgState {
        map: DashMap::new(),
        index: DashMap::new(),
        world_listeners: DashMap::new(),
    })
}

/// Sends notifications to scope-level and global world listeners.
fn notify_world_listeners(
    monitor: &PgState,
    scope: &ScopeName,
    group: &GroupName,
    actors: &[ActorCell],
    is_join: bool,
) {
    let scoped_key = ScopeGroupKey {
        scope: scope.to_owned(),
        group: ALL_GROUPS_NOTIFICATION.to_owned(),
    };
    let global_key = ScopeGroupKey {
        scope: ALL_SCOPES_NOTIFICATION.to_owned(),
        group: ALL_GROUPS_NOTIFICATION.to_owned(),
    };

    for key in [scoped_key, global_key] {
        let listeners = monitor
            .world_listeners
            .get(&key)
            .map(|entry| entry.value().clone());
        if let Some(listeners) = listeners {
            let change = if is_join {
                GroupChangeMessage::Join(scope.to_owned(), group.clone(), actors.to_vec())
            } else {
                GroupChangeMessage::Leave(scope.to_owned(), group.clone(), actors.to_vec())
            };
            for listener in &listeners {
                let _ = listener
                    .send_supervisor_evt(SupervisionEvent::ProcessGroupChanged(change.clone()));
            }
        }
    }
}

/// Join actors to the group `group` in the default scope
///
/// * `group` - The named group. Will be created if first actors to join
/// * `actors` - The list of [crate::Actor]s to add to the group
pub fn join(group: GroupName, actors: Vec<ActorCell>) {
    join_scoped(DEFAULT_SCOPE.to_owned(), group, actors);
}

/// Join actors to the group `group` within the scope `scope`
///
/// * `scope` - The named scope. Will be created if first actors to join
/// * `group` - The named group. Will be created if first actors to join
/// * `actors` - The list of [crate::Actor]s to add to the group
pub fn join_scoped(scope: ScopeName, group: GroupName, actors: Vec<ActorCell>) {
    let key = ScopeGroupKey {
        scope: scope.to_owned(),
        group: group.to_owned(),
    };
    let monitor = get_monitor();

    // Filter out actors that are already stopping or stopped
    let actors: Vec<ActorCell> = actors
        .into_iter()
        .filter(|a| (a.get_status() as u8) <= (ActorStatus::Draining as u8))
        .collect();

    if actors.is_empty() {
        return;
    }

    // Lock map entry, insert members, clone per-group listeners, then drop the guard
    let listeners = {
        let mut entry = monitor.map.entry(key).or_default();
        let gs = entry.value_mut();
        for actor in actors.iter() {
            gs.members.insert(actor.get_id(), actor.clone());
        }
        gs.listeners.clone()
    };

    // Update index
    monitor
        .index
        .entry(scope.to_owned())
        .or_default()
        .insert(group.to_owned());

    // Notify per-group listeners (guard already dropped)
    for listener in &listeners {
        let _ = listener.send_supervisor_evt(SupervisionEvent::ProcessGroupChanged(
            GroupChangeMessage::Join(scope.to_owned(), group.clone(), actors.clone()),
        ));
    }

    // Notify world listeners
    notify_world_listeners(monitor, &scope, &group, &actors, true);
}

/// Leaves the specified [crate::Actor]s from the PG group in the default scope
///
/// * `group` - A named group
/// * `actors` - The list of actors to remove from the group
pub fn leave(group: GroupName, actors: Vec<ActorCell>) {
    leave_scoped(DEFAULT_SCOPE.to_owned(), group, actors);
}

/// Leaves the specified [crate::Actor]s from the PG group within the scope `scope`
///
/// * `scope` - A named scope
/// * `group` - A named group
/// * `actors` - The list of actors to remove from the group
pub fn leave_scoped(scope: ScopeName, group: GroupName, actors: Vec<ActorCell>) {
    let key = ScopeGroupKey {
        scope: scope.to_owned(),
        group: group.to_owned(),
    };
    let monitor = get_monitor();

    // Lock map entry, remove members, clone listeners, check emptiness
    let result = if let Occupied(mut occupied) = monitor.map.entry(key) {
        let gs = occupied.get_mut();
        for actor in actors.iter() {
            gs.members.remove(&actor.get_id());
        }
        let listeners = gs.listeners.clone();
        let all_members_left = gs.members.is_empty();
        let fully_empty = all_members_left && gs.listeners.is_empty();
        if fully_empty {
            occupied.remove();
        }
        Some((listeners, all_members_left))
    } else {
        None
    };

    let Some((listeners, all_members_left)) = result else {
        return;
    };

    // Update index only if all members left
    if all_members_left {
        if let Some(mut groups) = monitor.index.get_mut(&scope) {
            groups.remove(&group);
            if groups.is_empty() {
                drop(groups);
                monitor.index.remove(&scope);
            }
        }
    }

    // Notify per-group listeners (guard already dropped)
    for listener in &listeners {
        let _ = listener.send_supervisor_evt(SupervisionEvent::ProcessGroupChanged(
            GroupChangeMessage::Leave(scope.to_owned(), group.clone(), actors.clone()),
        ));
    }

    // Notify world listeners
    notify_world_listeners(monitor, &scope, &group, &actors, false);
}

/// Leave all groups for a specific [ActorId].
/// Used only during actor shutdown
pub(crate) fn leave_all(actor: ActorId) {
    let monitor = get_monitor();

    // Phase 1: iterate, remove actor from members, collect notification info
    let mut removal_events: Vec<(ScopeGroupKey, ActorCell, Vec<ActorCell>)> = vec![];
    let mut empty_member_keys: Vec<ScopeGroupKey> = vec![];

    for mut kv in monitor.map.iter_mut() {
        let key = kv.key().clone();
        let gs = kv.value_mut();
        if let Some(actor_cell) = gs.members.remove(&actor) {
            let listeners = gs.listeners.clone();
            removal_events.push((key.clone(), actor_cell, listeners));
        }
        if gs.members.is_empty() {
            empty_member_keys.push(key);
        }
    }

    // Phase 2: clean up empty entries (re-check under lock to handle concurrent joins)
    for key in empty_member_keys {
        if let Occupied(entry) = monitor.map.entry(key.clone()) {
            if entry.get().members.is_empty() {
                // Update index
                if let Some(mut groups) = monitor.index.get_mut(&key.scope) {
                    groups.remove(&key.group);
                    if groups.is_empty() {
                        drop(groups);
                        monitor.index.remove(&key.scope);
                    }
                }
                // Only remove map entry if listeners are also empty
                if entry.get().listeners.is_empty() {
                    entry.remove();
                }
            }
        }
    }

    // Phase 3: send notifications (outside all locks)
    for (scope_and_group, cell, per_group_listeners) in removal_events.iter() {
        // Notify per-group listeners
        for listener in per_group_listeners {
            let _ = listener.send_supervisor_evt(SupervisionEvent::ProcessGroupChanged(
                GroupChangeMessage::Leave(
                    scope_and_group.scope.clone(),
                    scope_and_group.group.clone(),
                    vec![cell.clone()],
                ),
            ));
        }

        // Notify world listeners (scoped + global)
        notify_world_listeners(
            monitor,
            &scope_and_group.scope,
            &scope_and_group.group,
            std::slice::from_ref(cell),
            false,
        );
    }
}

/// Returns all actors running on the local node in the group `group`
/// in the default scope.
///
/// * `group` - A named group
///
/// Returns a [`Vec<ActorCell>`] representing the members of this paging group
pub fn get_local_members(group: &GroupName) -> Vec<ActorCell> {
    get_scoped_local_members(&DEFAULT_SCOPE.to_owned(), group)
}

/// Returns all actors running on the local node in the group `group`
/// in scope `scope`
///
/// * `scope_name` - A named scope
/// * `group_name` - A named group
///
/// Returns a [`Vec<ActorCell>`] representing the members of this paging group
pub fn get_scoped_local_members(scope: &ScopeName, group: &GroupName) -> Vec<ActorCell> {
    let key = ScopeGroupKey {
        scope: scope.to_owned(),
        group: group.to_owned(),
    };
    let monitor = get_monitor();
    if let Some(gs) = monitor.map.get(&key) {
        gs.value()
            .members
            .values()
            .filter(|a| a.get_id().is_local())
            .cloned()
            .collect::<Vec<_>>()
    } else {
        vec![]
    }
}

/// Returns all the actors running on any node in the group `group`
/// in the default scope.
///
/// * `group_name` - A named group
///
/// Returns a [`Vec<ActorCell>`] with the member actors
pub fn get_members(group_name: &GroupName) -> Vec<ActorCell> {
    get_scoped_members(&DEFAULT_SCOPE.to_owned(), group_name)
}

/// Returns all the actors running on any node in the group `group`
/// in the scope `scope`.
///
/// * `scope` - A named scope
/// * `group` - A named group
///
/// Returns a [`Vec<ActorCell>`] with the member actors
pub fn get_scoped_members(scope: &ScopeName, group: &GroupName) -> Vec<ActorCell> {
    let key = ScopeGroupKey {
        scope: scope.to_owned(),
        group: group.to_owned(),
    };
    let monitor = get_monitor();
    if let Some(gs) = monitor.map.get(&key) {
        gs.value().members.values().cloned().collect::<Vec<_>>()
    } else {
        vec![]
    }
}

/// Return a list of all known groups
///
/// Returns a [`Vec<GroupName>`] representing all the registered group names
pub fn which_groups() -> Vec<GroupName> {
    let monitor = get_monitor();
    let mut groups = monitor
        .map
        .iter()
        .filter(|kvp| !kvp.value().members.is_empty())
        .map(|kvp| kvp.key().group.to_owned())
        .collect::<Vec<_>>();
    groups.sort_unstable();
    groups.dedup();
    groups
}

/// Returns a list of all known groups in scope `scope`
///
/// * `scope` - The scope to retrieve the groups from
///
/// Returns a [`Vec<GroupName>`] representing all the registered group names
/// in `scope`
pub fn which_scoped_groups(scope: &ScopeName) -> Vec<GroupName> {
    let monitor = get_monitor();
    match monitor.index.get(scope) {
        Some(groups) => groups.iter().cloned().collect(),
        None => vec![],
    }
}

/// Returns a list of all known scope-group combinations.
///
/// Returns a [`Vec<ScopeGroupKey>`] representing all the registered
/// combinations that form an identifying tuple
pub fn which_scopes_and_groups() -> Vec<ScopeGroupKey> {
    let monitor = get_monitor();
    monitor
        .map
        .iter()
        .filter(|kvp| !kvp.value().members.is_empty())
        .map(|kvp| kvp.key().clone())
        .collect::<Vec<_>>()
}

/// Returns a list of all known scopes
///
/// Returns a [`Vec<ScopeName>`] representing all the registered scopes
pub fn which_scopes() -> Vec<ScopeName> {
    let monitor = get_monitor();
    monitor
        .map
        .iter()
        .filter(|kvp| !kvp.value().members.is_empty())
        .map(|kvp| kvp.key().scope.to_owned())
        .collect::<Vec<_>>()
}

/// Subscribes the provided [crate::Actor] to the group in the default scope
/// for updates
///
/// * `group_name` - The group to monitor
/// * `actor` - The [ActorCell] representing who will receive updates
pub fn monitor(group: GroupName, actor: ActorCell) {
    let key = ScopeGroupKey {
        scope: DEFAULT_SCOPE.to_owned(),
        group,
    };
    let monitor = get_monitor();
    monitor.map.entry(key).or_default().listeners.push(actor);
}

/// Subscribes the provided [crate::Actor] to the scope for updates
///
/// * `scope` - the scope to monitor
/// * `actor` - The [ActorCell] representing who will receive updates
pub fn monitor_scope(scope: ScopeName, actor: ActorCell) {
    let key = ScopeGroupKey {
        scope: scope.to_owned(),
        group: ALL_GROUPS_NOTIFICATION.to_owned(),
    };
    let monitor = get_monitor();
    // Register ONLY in world_listeners (not per-group) to avoid duplicate notifications
    monitor.world_listeners.entry(key).or_default().push(actor);
}

/// Unsubscribes the provided [crate::Actor] for updates from the group
/// in default scope
///
/// * `group_name` - The group to demonitor
/// * `actor` - The [ActorCell] representing who will no longer receive updates
pub fn demonitor(group_name: GroupName, actor: ActorId) {
    let key = ScopeGroupKey {
        scope: DEFAULT_SCOPE.to_owned(),
        group: group_name,
    };
    let monitor = get_monitor();
    if let Some(mut gs) = monitor.map.get_mut(&key) {
        gs.listeners.retain(|a| a.get_id() != actor);
    }
}

/// Unsubscribes the provided [crate::Actor] from the scope for updates
///
/// * `scope` - The scope to demonitor
/// * `actor` - The [ActorCell] representing who will no longer receive updates
pub fn demonitor_scope(scope: ScopeName, actor: ActorId) {
    let key = ScopeGroupKey {
        scope: scope.to_owned(),
        group: ALL_GROUPS_NOTIFICATION.to_owned(),
    };
    let monitor = get_monitor();
    if let Occupied(mut entry) = monitor.world_listeners.entry(key) {
        let listeners = entry.get_mut();
        listeners.retain(|a| a.get_id() != actor);
        if listeners.is_empty() {
            entry.remove();
        }
    }
}

/// Remove the specified [ActorId] from monitoring all groups it might be in.
/// Used only during actor shutdown
pub(crate) fn demonitor_all(actor: ActorId) {
    let monitor = get_monitor();

    // Remove from per-group listeners and track potentially empty entries
    let mut maybe_empty = vec![];
    for mut kv in monitor.map.iter_mut() {
        let gs = kv.value_mut();
        gs.listeners.retain(|a| a.get_id() != actor);
        if gs.members.is_empty() && gs.listeners.is_empty() {
            maybe_empty.push(kv.key().clone());
        }
    }

    // Clean up fully empty entries
    for key in maybe_empty {
        if let Occupied(entry) = monitor.map.entry(key.clone()) {
            if entry.get().members.is_empty() && entry.get().listeners.is_empty() {
                entry.remove();
                if let Some(mut groups) = monitor.index.get_mut(&key.scope) {
                    groups.remove(&key.group);
                    if groups.is_empty() {
                        drop(groups);
                        monitor.index.remove(&key.scope);
                    }
                }
            }
        }
    }

    // Remove from world listeners
    let mut empty_world_keys = vec![];
    for mut kv in monitor.world_listeners.iter_mut() {
        kv.value_mut().retain(|a| a.get_id() != actor);
        if kv.value().is_empty() {
            empty_world_keys.push(kv.key().clone());
        }
    }
    for key in empty_world_keys {
        monitor.world_listeners.remove(&key);
    }
}