Skip to main content

RactorRuntime

Struct RactorRuntime 

Source
pub struct RactorRuntime { /* private fields */ }
Expand description

A dactor v0.2 runtime backed by ractor.

Actors are spawned as real ractor actors via ractor::Actor::spawn. Messages are delivered through ractor’s mailbox as type-erased dispatch envelopes, supporting multiple Handler<M> impls per actor.

§System Actors

The runtime spawns native ractor system actors on creation:

System actors are accessible via system_actor_refs() for transport routing.

Implementations§

Source§

impl RactorRuntime

Source

pub const ADAPTER_NAME: &'static str = "ractor"

The adapter name for this runtime, used in version handshakes.

Source

pub fn new() -> Self

Create a new RactorRuntime.

System actors are not spawned until start_system_actors() is called. This allows the runtime to be constructed outside a tokio context.

Source

pub fn with_node_id(node_id: NodeId) -> Self

Create a new RactorRuntime with a specific node ID.

Source

pub fn with_app_version(self, version: impl Into<String>) -> Self

Set the application version for this node.

This is your application’s release version (e.g., “2.3.1”), not the dactor framework version. It is included in handshake requests for operational visibility during rolling upgrades.

Source

pub fn app_version(&self) -> Option<&str>

Returns the configured application version, if any.

Source

pub fn handshake_request(&self) -> HandshakeRequest

Build a HandshakeRequest from this runtime’s current configuration.

Source

pub async fn start_system_actors(&mut self)

Spawn native ractor system actors for transport routing.

Must be called from within a tokio runtime context. After this call, system_actor_refs() returns the native actor references.

Factory registrations made via register_factory() before this call are forwarded to the native SpawnManagerActor.

Uses default configuration (unbounded mailboxes, no pooling). For custom configuration, use [start_system_actors_with_config()].

Source

pub async fn start_system_actors_with_config( &mut self, config: SystemActorConfig, )

Spawn native ractor system actors with custom configuration.

Allows configuring mailbox capacity and SpawnManager pooling for high-throughput scenarios. See SystemActorConfig for details.

§Example
use dactor::system_actors::SystemActorConfig;
use dactor::mailbox::{MailboxConfig, OverflowStrategy};

let config = SystemActorConfig::default()
    .with_spawn_manager_mailbox(
        MailboxConfig::bounded(10_000, OverflowStrategy::Block)
    )
    .with_spawn_manager_pool_size(4)
    .with_control_plane_mailbox(
        MailboxConfig::bounded(5_000, OverflowStrategy::Block)
    );

runtime.start_system_actors_with_config(config).await;
Source

pub fn node_id(&self) -> &NodeId

Returns the node ID of this runtime.

Source

pub fn system_actor_refs(&self) -> Option<&RactorSystemActorRefs>

Access the native system actor references for transport routing.

Returns None if start_system_actors() has not been called yet.

Source

pub fn add_outbound_interceptor( &mut self, interceptor: Box<dyn OutboundInterceptor>, )

Add a global outbound interceptor.

Must be called before any actors are spawned. Panics if actors already hold references to the interceptor list (i.e., after spawn()).

Source

pub fn set_drop_observer(&mut self, observer: Arc<dyn DropObserver>)

Set a global drop observer that is notified whenever an outbound interceptor returns Disposition::Drop.

Source

pub fn set_dead_letter_handler(&mut self, handler: Arc<dyn DeadLetterHandler>)

Set a global dead letter handler. Called whenever a message cannot be delivered (actor stopped, mailbox full, dropped by inbound interceptor).

Source

pub fn cluster_events_handle(&self) -> &RactorClusterEvents

Access the cluster events subsystem.

Source

pub fn cluster_events(&self) -> &RactorClusterEvents

Access the cluster events subsystem.

Source

pub async fn spawn<A>( &self, name: &str, args: A::Args, ) -> Result<RactorActorRef<A>, RuntimeError>
where A: Actor<Deps = ()> + 'static,

Spawn an actor with Deps = ().

Source

pub async fn spawn_with_deps<A>( &self, name: &str, args: A::Args, deps: A::Deps, ) -> Result<RactorActorRef<A>, RuntimeError>
where A: Actor + 'static,

Spawn an actor with explicit dependencies.

Source

pub async fn spawn_with_options<A>( &self, name: &str, args: A::Args, options: SpawnOptions, ) -> Result<RactorActorRef<A>, RuntimeError>
where A: Actor<Deps = ()> + 'static,

Spawn an actor with spawn options (including inbound interceptors and mailbox config).

Source

pub fn watch<W>(&self, watcher: &RactorActorRef<W>, target_id: ActorId)
where W: Actor + Handler<ChildTerminated> + 'static,

Register actor watcher to be notified when target_id terminates.

The watcher must implement Handler<ChildTerminated>. When the target stops, the runtime delivers a ChildTerminated message to the watcher.

Source

pub fn unwatch(&self, watcher_id: &ActorId, target_id: &ActorId)

Unregister watcher_id from notifications about target_id.

Source

pub fn spawn_manager(&self) -> &SpawnManager

Access the spawn manager.

Source

pub fn spawn_manager_mut(&mut self) -> &mut SpawnManager

Access the spawn manager mutably (for registering actor factories).

Source

pub fn register_factory( &mut self, type_name: impl Into<String>, factory: impl Fn(&[u8]) -> Result<Box<dyn Any + Send>, SerializationError> + Send + Sync + 'static, )

Register an actor type for remote spawning on this node.

Registers the factory in both the struct-based SpawnManager and the native SpawnManagerActor (if started via start_system_actors()).

Source

pub fn handle_spawn_request( &mut self, request: &SpawnRequest, ) -> Result<(ActorId, Box<dyn Any + Send>), SpawnResponse>

Process a remote spawn request.

Looks up the actor type in the registry, deserializes Args from bytes, and returns the constructed actor along with its assigned ActorId.

The returned ActorId is pre-assigned for the remote spawn flow where the runtime controls ID assignment. The caller must use this ID when registering the spawned actor (not via the regular spawn() path, which assigns its own IDs).

Note: Currently uses the simple factory API (TypeRegistry::create_actor). For actors with non-trivial Deps, use spawn_manager_mut() to access TypeRegistry::create_actor_with_deps() directly.

Returns Ok((actor_id, actor)) on success, or Err(SpawnResponse::Failure) if the type is not found or deserialization fails.

Source

pub fn watch_manager(&self) -> &WatchManager

Access the watch manager (for remote watch subscriptions).

Source

pub fn watch_manager_mut(&mut self) -> &mut WatchManager

Access the watch manager mutably.

Source

pub fn remote_watch(&mut self, target: ActorId, watcher: ActorId)

Register a remote watch: a remote watcher wants to know when a local actor terminates.

Source

pub fn remote_unwatch(&mut self, target: &ActorId, watcher: &ActorId)

Remove a remote watch subscription.

Source

pub fn notify_terminated( &mut self, terminated: &ActorId, ) -> Vec<WatchNotification>

Called when a local actor terminates. Returns notifications for all remote watchers that should be sent to their respective nodes.

Note: This must be called explicitly by the integration layer. It is not yet automatically wired into ractor’s actor stop lifecycle.

Source

pub fn cancel_manager(&self) -> &CancelManager

Access the cancel manager.

Source

pub fn cancel_manager_mut(&mut self) -> &mut CancelManager

Access the cancel manager mutably.

Source

pub fn register_cancel(&mut self, request_id: String, token: CancellationToken)

Register a cancellation token for a request (for remote cancel support).

Source

pub fn cancel_request(&mut self, request_id: &str) -> CancelResponse

Process a remote cancellation request.

Source

pub fn complete_request(&mut self, request_id: &str)

Clean up a cancellation token after its request completes normally.

Should be called when a remote ask/stream/feed completes successfully to prevent stale tokens from accumulating.

Source

pub fn node_directory(&self) -> &NodeDirectory

Access the node directory.

Source

pub fn node_directory_mut(&mut self) -> &mut NodeDirectory

Access the node directory mutably.

Source

pub fn connect_peer(&mut self, peer_id: NodeId, address: Option<String>)

Register a peer node as connected in the directory.

Post-validation only: this method assumes the peer has already passed the version handshake. Callers should validate compatibility (via handshake_request + validate_handshake + verify_peer_identity) before calling this method. Direct calls bypass compatibility checks.

If the peer already exists, updates its status to Connected and preserves the existing address when address is None. Emits a ClusterEvent::NodeJoined if the peer was not previously connected.

Source

pub fn disconnect_peer(&mut self, peer_id: &NodeId)

Mark a peer as disconnected.

Emits a ClusterEvent::NodeLeft if the peer was previously connected.

Source

pub fn is_peer_connected(&self, peer_id: &NodeId) -> bool

Check if a peer node is connected.

Source

pub async fn await_stop(&self, actor_id: &ActorId) -> Result<(), String>

Wait for an actor to stop.

Returns Ok(()) when the actor finishes cleanly, or Err if the actor panicked in on_stop. The stop receiver is consumed and removed from the map.

Returns Ok(()) immediately if no stop receiver is stored for this ID (e.g., actor was already awaited or was not spawned by this runtime).

Source

pub async fn await_all(&self) -> Result<(), String>

Wait for all spawned actors to stop.

Drains all stored stop receivers and awaits them all. Returns the first error encountered, but always waits for every actor to finish.

Source

pub fn cleanup_finished(&self)

Remove completed stop receivers from the map.

Call periodically to prevent stale entries from accumulating for actors that stopped without being awaited.

Source

pub fn active_handle_count(&self) -> usize

Number of actors with stored stop receivers.

Note: includes receivers for actors that have already stopped but haven’t been awaited or cleaned up. Call cleanup_finished() first for an accurate count of running actors.

Trait Implementations§

Source§

impl Default for RactorRuntime

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl SystemMessageRouter for RactorRuntime

Source§

fn route_system_envelope<'life0, 'async_trait>( &'life0 self, envelope: WireEnvelope, ) -> Pin<Box<dyn Future<Output = Result<RoutingOutcome, RoutingError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Route a system message envelope to the appropriate system actor. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Message for T
where T: Any + Send + 'static,

Source§

fn from_boxed(m: BoxedMessage) -> Result<Self, BoxedDowncastErr>

Convert a BoxedMessage to this concrete type
Source§

fn box_message(self, pid: &ActorId) -> Result<BoxedMessage, BoxedDowncastErr>

Convert this message to a BoxedMessage
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> State for T
where T: Any + Send + 'static,