Struct elfo::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>(&mut self, source: UnattachedSource<S1>) -> S1where S1: SourceHandle,

Attaches the provided source to the context.

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 set_restart_policy(&self, policy: impl Into<Option<RestartPolicy>>)

Overrides the group’s default restart policy.

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>( &self, message: M ) -> impl Future<Output = Result<(), SendError<M>>>where M: Message,

Sends a message using the routing system.

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

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

// Fire or fail.
ctx.send(SomethingHappened).await?;

// Fire or log.
if let Ok(err) = ctx.send(SomethingHappened).await {
    warn!("...", error = err);
}
source

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

Tries to send a message using the routing system.

Returns

  • Ok(()) if the message has been added to any mailbox.
  • Err(Full(_)) if some mailboxes are full.
  • Err(Closed(_)) otherwise.
Example
// Fire and forget.
let _ = ctx.try_send(SomethingHappened);

// Fire or fail.
ctx.try_send(SomethingHappened)?;

// Fire or log.
if let Err(err) = ctx.try_send(SomethingHappened) {
    warn!("...", error = err);
}
source

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

Returns a request builder.

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>( &self, recipient: Addr, request: R ) -> RequestBuilder<'_, C, K, R, Any>where R: Request,

Returns a request builder 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>( &self, recipient: Addr, message: M ) -> impl Future<Output = Result<(), SendError<M>>>where M: Message,

Sends a message to the specified recipient.

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

Example
// Fire and forget.
let _ = ctx.send_to(addr, SomethingHappened).await;

// Fire or fail.
ctx.send_to(addr, SomethingHappened).await?;

// Fire or log.
if let Some(err) = ctx.send_to(addr, SomethingHappened).await {
    warn!("...", error = err);
}
source

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

Tries to send a message to the specified recipient.

Returns Err if the message hasn’t reached mailboxes or they are full.

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

// Fire or fail.
ctx.try_send_to(addr, SomethingHappened)?;

// Fire or log.
if let Some(err) = ctx.try_send_to(addr, SomethingHappened) {
    warn!("...", error = err);
}
source

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

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 ) -> impl Future<Output = Option<Envelope<AnyMessage>>>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.

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 ) -> impl Future<Output = Result<Envelope<AnyMessage>, 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.

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 unpack_config<'c>(&self, config: &'c AnyConfig) -> &'c Cwhere 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<(), Singleton>

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 for Context<C, K>where K: Clone,

source§

fn clone(&self) -> Context<C, K>

Returns a copy 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 = Singleton> !RefUnwindSafe for Context<C, K>

§

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

§

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

§

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

§

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

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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 Twhere 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.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> ToOwned for Twhere T: Clone,

§

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 Twhere U: Into<T>,

§

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 Twhere U: TryFrom<T>,

§

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