Struct ManagedAgent

Source
pub struct ManagedAgent<AgentState, Model: Default + Send + Debug + 'static> {
    pub model: Model,
    /* private fields */
}
Expand description

Represents an agent whose lifecycle and message processing are managed by the Acton framework.

ManagedAgent acts as a runtime wrapper around user-defined agent logic and state (Model). It utilizes a type-state pattern via the AgentState generic parameter (e.g., Idle, started::Started) to enforce valid operations during different phases of the agent’s lifecycle (configuration vs. active processing).

The framework handles the underlying task spawning, message reception from the inbox, dispatching messages to registered message_handlers, executing lifecycle hooks (like before_start, after_stop), and managing graceful shutdown via the halt_signal.

Users typically interact with ManagedAgent indirectly through an AgentHandle after the agent has been started, or directly during the configuration phase (when in the Idle state) to register message handlers and lifecycle hooks.

§Type Parameters

  • AgentState: A marker type (e.g., Idle, started::Started) indicating the current lifecycle state of the agent.
  • Model: The user-defined type containing the agent’s state and associated logic. It must implement Default, Send, Debug, and be 'static. Message handlers and lifecycle hooks operate on an instance of this Model.

Fields§

§model: Model

The user-defined state and logic associated with this agent.

This field holds the instance of the type provided as the Model generic parameter. Message handlers (registered via act_on in the Idle state) and lifecycle hooks (e.g., before_start, after_stop) receive mutable access to this model to implement the agent’s specific behavior and manage its data.

Implementations§

Source§

impl<State: Default + Send + Debug + 'static> ManagedAgent<Idle, State>

Source

pub fn act_on<M>( &mut self, message_processor: impl for<'a> Fn(&'a mut ManagedAgent<Started, State>, &'a mut MessageContext<M>) -> Pin<Box<dyn Future<Output = ()> + Send + Sync + 'static>> + Send + Sync + 'static, ) -> &mut Self
where M: ActonMessage + Clone + Send + Sync + 'static,

Registers an asynchronous message handler for a specific message type M.

This method is called during the agent’s configuration phase (while in the Idle state). It associates a specific message type M with a closure (message_processor) that will be executed when the agent receives a message of that type after it has started.

The framework handles the necessary type erasure and downcasting internally. The provided message_processor receives the agent (in the Started state) and a [MessageContext] containing the concrete message and metadata.

§Type Parameters
  • M: The concrete message type this handler will process. Must implement ActonMessage, Clone, Send, Sync, and be 'static.
§Arguments
  • message_processor: An asynchronous closure that takes the agent (&mut ManagedAgent<Started, State>) and the message context (&mut MessageContext<M>) and returns a Future (specifically, a [FutureBox]). This closure contains the logic for handling messages of type M.
§Returns

Returns a mutable reference to self to allow for method chaining during configuration.

Source

pub fn after_start<F, Fut>(&mut self, f: F) -> &mut Self
where F: for<'b> Fn(&'b ManagedAgent<Started, State>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + Sync + 'static,

Registers an asynchronous hook to be executed after the agent successfully starts its message loop.

This hook is called once, shortly after the agent transitions to the Started state and its main task begins processing messages. It receives an immutable reference to the agent in the Started state.

§Arguments
  • f: An asynchronous closure that takes &ManagedAgent<Started, State> and returns a Future.
§Returns

Returns a mutable reference to self for chaining.

Source

pub fn before_start<F, Fut>(&mut self, f: F) -> &mut Self
where F: for<'b> Fn(&'b ManagedAgent<Started, State>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + Sync + 'static,

Registers an asynchronous hook to be executed before the agent starts its message loop.

This hook is called once, just before the agent’s main task (wake) is spawned during the start process. It receives an immutable reference to the agent, technically still in the Started state contextually, though the loop hasn’t begun.

§Arguments
  • f: An asynchronous closure that takes &ManagedAgent<Started, State> and returns a Future.
§Returns

Returns a mutable reference to self for chaining.

Source

pub fn after_stop<F, Fut>(&mut self, f: F) -> &mut Self
where F: for<'b> Fn(&'b ManagedAgent<Started, State>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + Sync + 'static,

Registers an asynchronous hook to be executed after the agent stops processing messages.

This hook is called once when the agent’s main loop terminates gracefully (e.g., upon receiving a Terminate signal or when the inbox closes). It receives an immutable reference to the agent in the Started state context.

§Arguments
  • f: An asynchronous closure that takes &ManagedAgent<Started, State> and returns a Future.
§Returns

Returns a mutable reference to self for chaining.

Source

pub fn before_stop<F, Fut>(&mut self, f: F) -> &mut Self
where F: for<'b> Fn(&'b ManagedAgent<Started, State>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + Sync + 'static,

Registers an asynchronous hook to be executed before the agent stops processing messages.

This hook is called once, just before the agent’s main loop begins its shutdown sequence (e.g., after receiving Terminate but before fully stopping). It receives an immutable reference to the agent in the Started state.

§Arguments
  • f: An asynchronous closure that takes &ManagedAgent<Started, State> and returns a Future.
§Returns

Returns a mutable reference to self for chaining.

Source

pub async fn create_child( &self, name: String, ) -> Result<ManagedAgent<Idle, State>>

Creates the configuration for a new child agent under this agent’s supervision.

This method generates a ManagedAgent<Idle, State> instance pre-configured to be a child of the current agent. It automatically derives a hierarchical Ern for the child based on the parent’s ID and the provided name. The child inherits the parent’s broker reference.

The returned agent is in the Idle state and still needs to be configured (e.g., with act_on, lifecycle hooks) and then started using its start method. The parent agent typically calls handle.supervise(child_handle) after the child is started to register it formally.

§Arguments
  • name: The name segment for the child agent’s Ern.
§Returns

Returns a Result containing a new ManagedAgent instance for the child in the Idle state, ready for further configuration.

§Errors

Returns an error if creating the child’s Ern fails or if creating the AgentConfig fails (e.g., parsing the parent ID).

Source

pub async fn start(self) -> AgentHandle

Starts the agent’s processing loop and transitions it to the Started state.

This method consumes the ManagedAgent in the Idle state. It performs the following actions:

  1. Transitions the agent’s type state from Idle to Started.
  2. Executes the registered before_start lifecycle hook.
  3. Spawns the agent’s main asynchronous task (wake) which handles message processing.
  4. Closes the agent’s TaskTracker to signal that the main task has been spawned.
  5. Returns the agent’s AgentHandle for external interaction.

After this method returns, the agent is running and ready to process messages sent to its handle.

§Returns

An AgentHandle that can be used to interact with the now-running agent.

Source§

impl<Agent: Default + Send + Debug + 'static> ManagedAgent<Started, Agent>

Implements methods specific to a ManagedAgent in the Started state.

Source

pub fn new_envelope(&self) -> Option<OutboundEnvelope>

Creates a new OutboundEnvelope originating from this agent.

This helper function constructs an envelope suitable for sending a message from this agent to another recipient. The envelope’s return_address will be set to this agent’s MessageAddress. The recipient_address field will be None initially and should typically be set using the envelope’s methods before sending.

§Returns

An OutboundEnvelope configured with this agent as the sender. Returns None only if the agent’s handle somehow lacks an outbox, which should not occur under normal circumstances.

Source

pub fn new_parent_envelope(&self) -> Option<OutboundEnvelope>

Creates a new OutboundEnvelope addressed to this agent’s parent.

This is a convenience method for creating an envelope specifically for replying or sending a message to the agent that supervises this one. It clones the parent’s return address information.

§Returns
  • Some(OutboundEnvelope): An envelope configured to be sent to the parent, if this agent has a parent. The return_address will be the parent’s address, and the recipient_address will be this agent’s address.
  • None: If this agent does not have a parent (i.e., it’s a top-level agent).
Source§

impl<AgentState, Model: Default + Send + Debug + 'static> ManagedAgent<AgentState, Model>

Source

pub fn id(&self) -> &Ern

Returns a reference to the agent’s unique identifier (Ern).

Source

pub fn name(&self) -> &str

Returns the root name segment of the agent’s identifier (Ern).

Source

pub fn handle(&self) -> &AgentHandle

Returns a reference to the agent’s AgentHandle.

The handle is the primary means for external interaction with the agent once it has started.

Source

pub fn parent(&self) -> &Option<AgentHandle>

Returns a reference to the optional parent agent’s handle ([ParentRef]).

Returns None if this is a top-level agent.

Source

pub fn broker(&self) -> &AgentHandle

Returns a reference to the system message broker’s handle ([BrokerRef]).

Source

pub fn runtime(&self) -> &AgentRuntime

Returns a reference to the AgentRuntime this agent belongs to.

Trait Implementations§

Source§

impl<AgentState, Model: Default + Send + Debug + 'static> Debug for ManagedAgent<AgentState, Model>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<State: Default + Send + Debug + 'static> Default for ManagedAgent<Idle, State>

Source§

fn default() -> Self

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

impl<State: Default + Send + Debug + 'static> From<ManagedAgent<Idle, State>> for ManagedAgent<Started, State>

Source§

fn from(value: ManagedAgent<Idle, State>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<AgentState, Model> !Freeze for ManagedAgent<AgentState, Model>

§

impl<AgentState, Model> !RefUnwindSafe for ManagedAgent<AgentState, Model>

§

impl<AgentState, Model> Send for ManagedAgent<AgentState, Model>
where AgentState: Send,

§

impl<AgentState, Model> Sync for ManagedAgent<AgentState, Model>
where Model: Sync, AgentState: Sync,

§

impl<AgentState, Model> Unpin for ManagedAgent<AgentState, Model>
where Model: Unpin, AgentState: Unpin,

§

impl<AgentState, Model> !UnwindSafe for ManagedAgent<AgentState, Model>

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> Same for T

Source§

type Output = T

Should always be Self
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