Skip to main content

Ctx

Struct Ctx 

Source
pub struct Ctx<P>
where P: Actor,
{ /* private fields */ }
Expand description

The context surrounding the current Actor.

Provides a collection of methods that allow you to:

  • spawn other actors as children of the current actor
  • access the Handle<_> for the currrent actor
  • access this actor’s props
  • clear this actor’s mailbox

Implementations§

Source§

impl<P: Actor> Ctx<P>

Source

pub fn subscribe<T>(&mut self, topic: &str) -> Result<(), PubSubError>
where T: Clone + Send + 'static, P::Msg: From<T>,

Subscribes this actor to a topic. Messages published to the topic will be cloned, converted via From<T> into this actor’s Msg type, and delivered to this actor’s mailbox.

Returns PubSubError::TypeMismatch if the topic was already created with a different message type.

Source

pub fn publish<T: Send + 'static>( &self, topic: &str, msg: T, ) -> Result<(), PubSubError>

Publishes a message to all subscribers of a topic. The message is cloned for each subscriber.

Publishing to a topic with no subscribers is a no-op and returns Ok(()). Returns PubSubError::TypeMismatch if the topic exists with a different type.

Source§

impl<P> Ctx<P>
where P: Actor,

Source

pub fn props(&self) -> &P::Props

Returns a reference to this Actor’s props. Props are set once at spawn time and remain immutable for the lifetime of the actor, including across restarts.

§Example
async fn init(ctx: &mut Ctx<Self>) -> Result<Self, Self::Err> {
    Ok(MyActor { count: ctx.props().initial_count })
}
Source

pub fn this(&self) -> &Handle<P::Msg>

Returns a Handle to the current Actor, allowing it to send messages to itself or pass its handle to child actors.

§Example
// schedule a message to self
ctx.this().send_in(Msg::Tick, Duration::from_secs(1));
Source

pub fn clear_mailbox(&self)

Drains all pending messages from this Actor’s mailbox. Useful during restarts to discard stale messages via Actor::init.

§Example
async fn init(ctx: &mut Ctx<Self>) -> Result<Self, Self::Err> {
    ctx.clear_mailbox();
    Ok(MyActor::default())
}
Source

pub fn actor<'a, Child>( &'a mut self, props: Child::Props, ) -> SpawnBuilder<'a, P, Child>
where Child: Actor,

Creates a SpawnBuilder for spawning a child Actor. The actor type is passed as a generic parameter and its props as the argument. The child is supervised by the current actor and will be stopped when the parent stops.

§Example
let handle = ctx.actor::<Worker>(WorkerProps { id: 1 })
    .supervision(Supervision::Restart {
        max: Limit::Amount(3),
        backoff: Backoff::None,
    })
    .spawn();
Source

pub fn restart_children(&self)

Restarts all child actors immediately, bypassing their supervision strategy. Each child will re-run its Actor::init with the same props.

This is fire-and-forget: it does not wait for children to finish restarting.

Source

pub async fn stop_children(&mut self)

Stops all child actors and waits for each to fully terminate before returning.

Source

pub fn task<F>(&mut self, f: F)
where F: Future<Output = Result<P::Msg, P::Err>> + Send + 'static,

Spawns a background async task. On completion, its Ok value is delivered as a message to this Actor; its Err triggers the supervision strategy that this actor’s parent has set for it.

Tasks are aborted when the actor stops, but survive restarts. If the actor is restarted (via supervision or Ctx::restart_children), in-flight tasks from the previous incarnation will continue running and their results will still be delivered to the restarted actor’s handle().

§Example
ctx.task(async {
    let data = reqwest::get("https://example.com").await?.text().await?;
    Ok(Msg::Fetched(data))
});
Source

pub fn get_handle_for<A: Actor>(&self) -> Result<Handle<A::Msg>, RegistryError>

Looks up a registered Actor’s Handle by its type. The actor must have been spawned with SpawnBuilder::spawn_registered.

§Example
let logger = ctx.get_handle_for::<Logger>()?;
logger.send(LogMsg::Info("hello".into()));
Source

pub fn get_handle<Msg: Send + 'static>( &self, name: &str, ) -> Result<Handle<Msg>, RegistryError>

Looks up a registered Actor’s Handle by name. The actor must have been spawned with SpawnBuilder::spawn_named.

§Example
let worker = ctx.get_handle::<WorkerMsg>("worker-1")?;
worker.send(WorkerMsg::Start);
Source

pub fn send<A: Actor>( &self, msg: impl Into<A::Msg>, ) -> Result<(), RegistryError>

Sends a message to a registered Actor looked up by type.

§Example
// Assuming MetricsCollector was spawned with spawn_registered():
// ctx.actor::<MetricsCollector>(props).spawn_registered()?;

// Any actor in the system can then send to it by type:
ctx.send::<MetricsCollector>(MetricsMsg::RecordLatency(42))?;
Source

pub fn send_to<Msg: Send + 'static>( &self, name: &str, msg: impl Into<Msg>, ) -> Result<(), RegistryError>

Sends a message to a registered Actor looked up by name.

§Example
// Assuming a Worker was spawned with spawn_named():
// ctx.actor::<Worker>(props).spawn_named("worker-1")?;

// Any actor in the system can then send to it by name:
ctx.send_to("worker-1", WorkerMsg::Start)?;

Auto Trait Implementations§

§

impl<P> Freeze for Ctx<P>
where <P as Actor>::Props: Freeze,

§

impl<P> RefUnwindSafe for Ctx<P>
where <P as Actor>::Props: RefUnwindSafe,

§

impl<P> Send for Ctx<P>

§

impl<P> Sync for Ctx<P>
where <P as Actor>::Props: Sync,

§

impl<P> Unpin for Ctx<P>
where <P as Actor>::Props: Unpin,

§

impl<P> UnsafeUnpin for Ctx<P>
where <P as Actor>::Props: UnsafeUnpin,

§

impl<P> UnwindSafe for Ctx<P>
where <P as Actor>::Props: UnwindSafe,

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, 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, 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.