Skip to content

Commit

Permalink
Large cleanup (#281)
Browse files Browse the repository at this point in the history
1. [COMPAT BREAK] Switch to `bon::Builder` for factory arguments and settings which gives compile-time, vs run-time, safety constructing types.
2. Cleanup a lot of debug impl's
3. Cleanup comments in various places.

And bump the version to 0.13.0 because of the migration to bon
  • Loading branch information
slawlor authored Oct 25, 2024
1 parent 9fe3d19 commit 3914f6d
Show file tree
Hide file tree
Showing 22 changed files with 185 additions and 387 deletions.
3 changes: 2 additions & 1 deletion ractor/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "ractor"
version = "0.12.4"
version = "0.13.0"
authors = ["Sean Lawlor", "Evan Au", "Dillon George"]
description = "A actor framework for Rust"
documentation = "https://docs.rs/ractor"
Expand All @@ -26,6 +26,7 @@ default = ["tokio_runtime", "async-trait"]

[dependencies]
## Required dependencies
bon = "2"
dashmap = "6"
futures = "0.3"
once_cell = "1"
Expand Down
23 changes: 18 additions & 5 deletions ractor/src/actor/actor_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,11 +201,24 @@ pub struct ActorCell {

impl std::fmt::Debug for ActorCell {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(name) = self.get_name() {
write!(f, "Actor '{}' (id: {})", name, self.get_id())
} else {
write!(f, "Actor with id: {}", self.get_id())
}
f.debug_struct("Actor")
.field("name", &self.get_name())
.field("id", &self.get_id())
.finish()
}
}

impl PartialEq for ActorCell {
fn eq(&self, other: &Self) -> bool {
other.get_id() == self.get_id()
}
}

impl Eq for ActorCell {}

impl std::hash::Hash for ActorCell {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.get_id().hash(state)
}
}

Expand Down
13 changes: 11 additions & 2 deletions ractor/src/actor/actor_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,28 @@ impl ActorId {
/// Determine if this actor id is a local or remote actor
///
/// Returns [true] if it is a local actor, [false] otherwise
pub fn is_local(&self) -> bool {
pub const fn is_local(&self) -> bool {
matches!(self, ActorId::Local(_))
}

/// Retrieve the actor's PID
///
/// Returns the actor's [u64] instance identifier (process id).
pub fn pid(&self) -> u64 {
pub const fn pid(&self) -> u64 {
match self {
ActorId::Local(pid) => *pid,
ActorId::Remote { pid, .. } => *pid,
}
}

/// Retrieve the node id of this PID. 0 = a local actor, while
/// any non-zero value is the ide of the remote node running this actor
pub const fn node(&self) -> u64 {
match self {
ActorId::Local(_) => 0,
ActorId::Remote { node_id, .. } => *node_id,
}
}
}

impl Display for ActorId {
Expand Down
13 changes: 5 additions & 8 deletions ractor/src/actor/actor_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

//! [ActorRef] is a strongly-typed wrapper over an [ActorCell]
use std::any::TypeId;
use std::marker::PhantomData;

use crate::{ActorName, Message, MessagingErr, SupervisionEvent};
Expand Down Expand Up @@ -57,7 +56,7 @@ impl<TActor> From<ActorRef<TActor>> for ActorCell {

impl<TMessage> std::fmt::Debug for ActorRef<TMessage> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.inner)
self.inner.fmt(f)
}
}

Expand Down Expand Up @@ -101,13 +100,11 @@ where
pub fn where_is(name: ActorName) -> Option<crate::actor::ActorRef<TMessage>> {
if let Some(actor) = crate::registry::where_is(name) {
// check the type id when pulling from the registry
if actor.get_type_id() == TypeId::of::<TMessage>() {
Some(actor.into())
} else {
None
let check = actor.is_message_type_of::<TMessage>();
if check.is_none() || matches!(check, Some(true)) {
return Some(actor.into());
}
} else {
None
}
None
}
}
17 changes: 3 additions & 14 deletions ractor/src/actor/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub struct BoxedState {

impl Debug for BoxedState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "BoxedState")
f.debug_struct("BoxedState").finish()
}
}

Expand Down Expand Up @@ -61,19 +61,14 @@ impl BoxedState {
}

/// Messages to stop an actor
#[derive(Debug)]
pub enum StopMessage {
/// Normal stop
Stop,
/// Stop with a reason
Reason(String),
}

impl Debug for StopMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Stop message: {self}")
}
}

impl std::fmt::Display for StopMessage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Expand Down Expand Up @@ -172,18 +167,12 @@ impl std::fmt::Display for SupervisionEvent {
}

/// A signal message which takes priority above all else
#[derive(Clone)]
#[derive(Clone, Debug)]
pub enum Signal {
/// Terminate the agent, cancelling all async work immediately
Kill,
}

impl Debug for Signal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Signal: {self}")
}
}

impl std::fmt::Display for Signal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Expand Down
11 changes: 5 additions & 6 deletions ractor/src/actor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ pub(crate) fn get_panic_string(e: Box<dyn std::any::Any + Send>) -> ActorProcess
/// * `post_stop`
/// * `handle`
/// * `handle_serialized` (Available with `cluster` feature only)
/// * `handle_supervision_evt`
/// * `handle_supervisor_evt`
///
/// return a [Result<_, ActorProcessingError>] where the error type is an
/// alias of [Box<dyn std::error::Error + Send + Sync + 'static>]. This is treated
Expand Down Expand Up @@ -481,11 +481,10 @@ where

impl<TActor: Actor> Debug for ActorRuntime<TActor> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(name) = self.name.as_ref() {
write!(f, "ActorRuntime('{}' - {})", name, self.id)
} else {
write!(f, "ActorRuntime({})", self.id)
}
f.debug_struct("ActorRuntime")
.field("name", &self.name)
.field("id", &self.id)
.finish()
}
}

Expand Down
36 changes: 5 additions & 31 deletions ractor/src/actor/supervision.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,7 @@ impl SupervisionTree {
/// from the supervision tree since the supervisor is shutting down
/// and can't deal with superivison events anyways
pub(crate) fn terminate_all_children(&self) {
let mut guard = self.children.lock().unwrap();
let cells = guard.iter().map(|(_, a)| a.clone()).collect::<Vec<_>>();
guard.clear();
// drop the guard to not deadlock on double-link
drop(guard);
let cells = self.get_children();
for cell in cells {
cell.terminate();
cell.clear_supervisor();
Expand All @@ -65,23 +61,15 @@ impl SupervisionTree {

/// Stop all the linked children, but does NOT unlink them (stop flow will do that)
pub(crate) fn stop_all_children(&self, reason: Option<String>) {
let mut guard = self.children.lock().unwrap();
let cells = guard.iter().map(|(_, a)| a.clone()).collect::<Vec<_>>();
guard.clear();
// drop the guard to not deadlock on double-link
drop(guard);
let cells = self.get_children();
for cell in cells {
cell.stop(reason.clone());
}
}

/// Drain all the linked children, but does NOT unlink them
pub(crate) fn drain_all_children(&self) {
let mut guard = self.children.lock().unwrap();
let cells = guard.iter().map(|(_, a)| a.clone()).collect::<Vec<_>>();
guard.clear();
// drop the guard to not deadlock on double-link
drop(guard);
let cells = self.get_children();
for cell in cells {
_ = cell.drain();
}
Expand All @@ -94,14 +82,7 @@ impl SupervisionTree {
reason: Option<String>,
timeout: Option<crate::concurrency::Duration>,
) {
let cells;
{
let mut guard = self.children.lock().unwrap();
cells = guard.iter().map(|(_, a)| a.clone()).collect::<Vec<_>>();
guard.clear();
// drop the guard to not deadlock on double-link
drop(guard);
}
let cells = self.get_children();
let mut js = crate::concurrency::JoinSet::new();
for cell in cells {
let lreason = reason.clone();
Expand All @@ -116,14 +97,7 @@ impl SupervisionTree {
&self,
timeout: Option<crate::concurrency::Duration>,
) {
let cells;
{
let mut guard = self.children.lock().unwrap();
cells = guard.iter().map(|(_, a)| a.clone()).collect::<Vec<_>>();
guard.clear();
// drop the guard to not deadlock on double-link
drop(guard);
}
let cells = self.get_children();
let mut js = crate::concurrency::JoinSet::new();
for cell in cells {
let ltimeout = timeout;
Expand Down
2 changes: 2 additions & 0 deletions ractor/src/actor/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,8 @@ fn returns_actor_references() {
];

for (want, event) in tests {
// Cloned cells are "equal" since they point to the same actor id
assert_eq!(event.actor_cell(), event.actor_cell().clone());
assert_eq!(event.actor_cell().is_some(), want);
assert_eq!(event.actor_id().is_some(), want);
}
Expand Down
Loading

0 comments on commit 3914f6d

Please sign in to comment.