Skip to main content

Context

Struct Context 

Source
pub struct Context<C = (), K = Singleton> { /* private fields */ }
Expand description

An actor execution context.

Implementations§

Source§

impl<C, K> Context<C, K>

Source

pub fn addr(&self) -> Addr

Returns the actor’s address.

Source

pub fn group(&self) -> Addr

Returns the current group’s address.

Source

pub fn config(&self) -> &C

Returns the actual config.

Source

pub fn key(&self) -> &K

Returns the actor’s key.

Source

pub fn attach<S1: SourceHandle>(&mut self, source: UnattachedSource<S1>) -> S1

Attaches the provided source to the context.

Messages produced by the source will be available via Context::recv() and Context::try_recv() methods.

Source

pub fn set_status(&self, status: ActorStatus)

Updates the actor’s status.

§Example
ctx.set_status(elfo::ActorStatus::ALARMING.with_details("something wrong"));
Source

pub fn status_kind(&self) -> ActorStatusKind

Gets the actor’s status kind.

§Example
// if actor is terminating.
assert!(ctx.status_kind().is_terminating());
// if actor is alarming.
assert!(ctx.status_kind().is_alarming());
// and so on...
§Panics

Panics when called on pruned context.

Source

pub fn set_mailbox_capacity(&self, capacity: impl Into<Option<usize>>)

Overrides the group’s default mailbox capacity, which set in the config.

Note: after restart the actor will be created from scratch, so this override will be also reset to the group’s default mailbox capacity.

§Example
// Override the group's default mailbox capacity.
ctx.set_mailbox_capacity(42);

// Set the group's default mailbox capacity.
ctx.set_mailbox_capacity(None);
Source

pub fn set_restart_policy(&self, policy: impl Into<Option<RestartPolicy>>)

Overrides the group’s default restart policy, which set in the config.

Note: after restart the actor will be created from scratch, so this override will be also reset to the group’s default restart policy.

§Example
// Override the group's default restart policy.
ctx.set_restart_policy(elfo::RestartPolicy::never());

// Set the group's default restart policy.
ctx.set_restart_policy(None);
Source

pub fn close(&self) -> bool

Closes the mailbox, that leads to returning None from recv() and try_recv() after handling all available messages in the mailbox.

Returns true if the mailbox has just been closed.

Source

pub async fn send<M: Message>(&self, message: M) -> Result<(), SendError<M>>

Sends a message using the inter-group routing system.

It’s possible to send requests if the response is not needed.

Returns Err if the message hasn’t reached any mailboxes.

§Cancel safety

If cancelled, recipients with full mailboxes wont’t receive the message.

§Example
#[message]
struct SomethingHappened;

// Fire and forget.
let _ = ctx.send(SomethingHappened).await;

// Fire or log.
if let Err(error) = ctx.send(SomethingHappened).await {
    tracing::warn!(%error, "...");
}
Source

pub fn try_send<M: Message>(&self, message: M) -> Result<(), TrySendError<M>>

Tries to send a message using the inter-group routing system.

It’s possible to send requests if the response is not needed.

Returns

  • Ok(()) if the message has been added to any mailbox.
  • Err(Full(_)) if some mailboxes are full.
  • Err(Closed(_)) otherwise.
§Example
#[message]
struct SomethingHappened;

// Fire and forget.
let _ = ctx.try_send(SomethingHappened);

// Fire or log.
if let Err(error) = ctx.try_send(SomethingHappened) {
    tracing::warn!(%error, "...");
}
Source

pub fn unbounded_send<M: Message>(&self, message: M) -> Result<(), SendError<M>>

Sends a message using the inter-group routing system. Affects other senders.

Usually this method shouldn’t be used because it can lead to high memory usage and even OOM if the recipient works too slowly. Prefer Context::try_send() or Context::send() instead.

It’s possible to send requests if the response is not needed.

Returns Err if the message hasn’t reached mailboxes.

§Example
#[message]
struct SomethingHappened;

// Fire and forget.
let _ = ctx.unbounded_send(SomethingHappened);

// Fire or log.
if let Err(error) = ctx.unbounded_send(SomethingHappened) {
    tracing::warn!(%error, "...");
}
Source

pub fn request<R: Request>( &self, request: R, ) -> RequestBuilder<'_, C, K, R, Any>

Returns a request builder to send a request (on resolve()) using the inter-group routing system.

§Example
// Request and wait for a response.
let response = ctx.request(SomeCommand).resolve().await?;

// Request and wait for all responses.
for result in ctx.request(SomeCommand).all().resolve().await {
    // ...
}
Source

pub fn request_to<R: Request>( &self, recipient: Addr, request: R, ) -> RequestBuilder<'_, C, K, R, Any>

Returns a request builder to send a request to the specified recipient.

§Example
// Request and wait for a response.
let response = ctx.request_to(addr, SomeCommand).resolve().await?;

// Request and wait for all responses.
for result in ctx.request_to(addr, SomeCommand).all().resolve().await {
    // ...
}
Source

pub async fn send_to<M: Message>( &self, recipient: Addr, message: M, ) -> Result<(), SendError<M>>

Sends a message to the specified recipient. Waits if the recipient’s mailbox is full.

It’s possible to send requests if the response is not needed.

Returns Err if the message hasn’t reached any mailboxes.

§Cancel safety

If cancelled, recipients with full mailboxes wont’t receive the message.

§Example
#[message]
struct SomethingHappened;

let _ = ctx.send_to(addr, SomethingHappened).await;

// Fire or log.
if let Err(error) = ctx.send_to(addr, SomethingHappened).await {
    tracing::warn!(%error, "...");
}
Source

pub fn try_send_to<M: Message>( &self, recipient: Addr, message: M, ) -> Result<(), TrySendError<M>>

Tries to send a message to the specified recipient. Returns an error if the recipient’s mailbox is full.

It’s possible to send requests if the response is not needed.

Returns

  • Ok(()) if the message has been added to any mailbox.
  • Err(Full(_)) if some mailboxes are full.
  • Err(Closed(_)) otherwise.
§Example
#[message]
struct SomethingHappened;

// Fire and forget.
let _ = ctx.try_send_to(addr, SomethingHappened);

// Fire or log.
if let Err(error) = ctx.try_send_to(addr, SomethingHappened) {
    tracing::warn!(%error, "...");
}
Source

pub fn unbounded_send_to<M: Message>( &self, recipient: Addr, message: M, ) -> Result<(), SendError<M>>

Sends a message to the specified recipient. Affects other senders.

Usually this method shouldn’t be used because it can lead to high memory usage and even OOM if the recipient works too slowly. Prefer Context::try_send_to() or Context::send_to() instead.

It’s possible to send requests if the response is not needed.

Returns Err if the message hasn’t reached mailboxes.

§Example
#[message]
struct SomethingHappened;

// Fire and forget.
let _ = ctx.unbounded_send_to(addr, SomethingHappened);

// Fire or log.
if let Err(error) = ctx.unbounded_send_to(addr, SomethingHappened) {
    tracing::warn!(%error, "...");
}
Source

pub fn respond<R: Request>(&self, token: ResponseToken<R>, message: R::Response)

Responds to the requester with the provided response.

The token can be used only once.

msg!(match envelope {
    (SomeRequest, token) => {
        ctx.respond(token, SomeResponse);
    }
})
Source

pub async fn recv(&mut self) -> Option<Envelope>
where C: 'static,

Receives the next envelope from the mailbox or sources. If the envelope isn’t available, the method waits for the next one. If the mailbox is closed, None is returned.

§Budget

The method returns the execution back to the runtime once the actor’s budget has been exhausted. It prevents the actor from blocking the runtime for too long. See coop for details.

§Cancel safety

This method is cancel safe. However, using select! requires handling tracing on your own, so avoid it if possible (use sources instead).

§Panics

If the method is called again after None is returned.

§Example
while let Some(envelope) = ctx.recv().await {
    msg!(match envelope {
        SomethingHappened => { /* ... */ },
    });
}
Source

pub async fn try_recv(&mut self) -> Result<Envelope, TryRecvError>
where C: 'static,

Receives the next envelope from the mailbox or sources without waiting. If the envelope isn’t available, Err(TryRecvError::Empty) is returned. If the mailbox is closed, Err(TryRecvError::Closed) is returned. Useful to batch message processing.

The method is async due to the following reasons:

  1. To poll sources, not only the mailbox.
  2. To respect the actor budget (see below).
§Budget

The method returns the execution back to the runtime once the actor’s budget has been exhausted. It prevents the actor from blocking the runtime for too long. See coop for details.

§Cancel safety

This method is cancel safe. However, using select! requires handling tracing on your own, so avoid it if possible (use sources instead).

§Panics

If the method is called again after Err(TryRecvError::Closed).

§Example

Handle all available messages:

let mut batch = Vec::new();

loop {
    match ctx.try_recv().await {
        Ok(envelope) => batch.push(envelope),
        Err(err) => {
            handle_batch(batch.drain(..));

            if err.is_empty() {
                // Wait for the next batch.
                if let Some(envelope) = ctx.recv().await {
                    batch.push(envelope);
                    continue;
                }
            }

            break;
        },
    }
}
Source

pub fn start_info(&self) -> &ActorStartInfo

Retrieves information related to the start of the actor.

§Panics

This method will panic if the context is pruned, indicating that the required information is no longer available.

§Example
match ctx.start_info().cause {
    ActorStartCause::GroupMounted => {
        // The actor started because its group was mounted.
    }
    ActorStartCause::OnMessage => {
        // The actor started in response to a message.
    }
    ActorStartCause::Restarted => {
        // The actor started due to the restart policy.
    }
    _ => {}
}
Source

pub fn unpack_config<'c>(&self, config: &'c AnyConfig) -> &'c C
where C: for<'de> Deserialize<'de> + 'static,

Used to get the typed config from ValidateConfig.

msg!(match envelope {
    (ValidateConfig { config, .. }, token) => {
        let new_config = ctx.unpack_config(&config);
        ctx.respond(token, Err("oops".into()));
    }
})
Source

pub fn pruned(&self) -> Context

Produces a new context that can be used for sending messages only.

Pruned contexts are likely to be removed in favor of Output.

Trait Implementations§

Source§

impl<C, K: Clone> Clone for Context<C, K>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl<C, K> Freeze for Context<C, K>
where K: Freeze,

§

impl<C = (), K = Singleton> !RefUnwindSafe for Context<C, K>

§

impl<C, K> Send for Context<C, K>
where K: Send, C: Sync + Send,

§

impl<C, K> Sync for Context<C, K>
where K: Sync, C: Sync + Send,

§

impl<C, K> Unpin for Context<C, K>
where K: Unpin,

§

impl<C, K> UnsafeUnpin for Context<C, K>
where K: UnsafeUnpin,

§

impl<C = (), K = Singleton> !UnwindSafe for Context<C, K>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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