acton_core/common/
agent_handle.rs

1/*
2 * Copyright (c) 2024. Govcraft
3 *
4 * Licensed under either of
5 *   * Apache License, Version 2.0 (the "License");
6 *     you may not use this file except in compliance with the License.
7 *     You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8 *   * MIT license: http://opensource.org/licenses/MIT
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the applicable License for the specific language governing permissions and
14 * limitations under that License.
15 */
16use std::fmt::Debug;
17use std::future::Future;
18use std::hash::{Hash, Hasher};
19
20use acton_ern::Ern;
21use async_trait::async_trait;
22use dashmap::DashMap;
23use tokio::sync::mpsc;
24use tokio_util::task::TaskTracker;
25use tracing::{error, instrument, trace, warn}; // warn seems unused
26
27use crate::actor::{Idle, ManagedAgent};
28use crate::common::{AgentSender, BrokerRef, OutboundEnvelope, ParentRef};
29use crate::message::{BrokerRequest, MessageAddress, SystemSignal};
30use crate::prelude::ActonMessage;
31use crate::traits::{AgentHandleInterface, Broker, Subscriber};
32
33/// A clonable handle for interacting with an agent.
34///
35/// `AgentHandle` provides the primary mechanism for communicating with and managing
36/// an agent from outside its own execution context. It encapsulates the necessary
37/// information to send messages to the agent's inbox (`outbox`), identify the agent (`id`),
38/// manage its lifecycle (`stop`), track its tasks (`tracker`), and navigate the
39/// supervision hierarchy (`parent`, `children`, `supervise`).
40///
41/// Handles can be cloned freely, allowing multiple parts of the system to hold references
42/// to the same agent. Sending messages through the handle is asynchronous.
43///
44/// Key functionalities are exposed through implemented traits:
45/// *   [`AgentHandleInterface`]: Core methods for interaction (sending messages, stopping, etc.).
46/// *   [`Broker`]: Methods for broadcasting messages via the system broker.
47/// *   [`Subscriber`]: Method for accessing the system broker handle.
48///
49/// Equality and hashing are based solely on the agent's unique identifier (`id`).
50#[derive(Debug, Clone)]
51pub struct AgentHandle {
52    /// The unique identifier (`Ern`) for the agent this handle refers to.
53    pub(crate) id: Ern,
54    /// The sender part of the MPSC channel connected to the agent's inbox.
55    pub(crate) outbox: AgentSender,
56    /// Tracks the agent's main task and potentially other associated tasks.
57    tracker: TaskTracker,
58    /// Optional reference to the parent (supervisor) agent's handle.
59    /// `None` if this is a top-level agent. Boxed to manage `AgentHandle` size.
60    pub parent: Option<Box<ParentRef>>,
61    /// Optional reference to the system message broker's handle.
62    /// Boxed to manage `AgentHandle` size.
63    pub broker: Box<Option<BrokerRef>>,
64    /// A map holding handles to the direct children supervised by this agent.
65    /// Keys are the string representation of the child agent's `Ern`.
66    children: DashMap<String, AgentHandle>,
67    /// The agent's cancellation token (clone).
68    pub(crate) cancellation_token: tokio_util::sync::CancellationToken,
69}
70
71impl Default for AgentHandle {
72    /// Creates a default, placeholder `AgentHandle`.
73    ///
74    /// This handle is typically initialized with a default `Ern`, a closed channel,
75    /// and no parent, broker, or children. It's primarily used as a starting point
76    /// before being properly configured when a `ManagedAgent` is created.
77    fn default() -> Self {
78        use crate::common::config::CONFIG;
79        
80        let dummy_channel_size = CONFIG.limits.dummy_channel_size;
81        let (outbox, _) = mpsc::channel(dummy_channel_size); // Create a dummy channel
82        AgentHandle {
83            id: Ern::default(),
84            outbox,
85            tracker: TaskTracker::new(),
86            parent: None,
87            broker: Box::new(None),
88            children: DashMap::new(),
89            cancellation_token: tokio_util::sync::CancellationToken::new(),
90        }
91    }
92}
93
94/// Implements the `Subscriber` trait, allowing access to the broker.
95impl Subscriber for AgentHandle {
96    /// Returns a clone of the optional broker handle associated with this agent.
97    ///
98    /// Returns `None` if the agent was not configured with a broker reference.
99    fn get_broker(&self) -> Option<BrokerRef> {
100        *self.broker.clone() // Clone the Option<BrokerRef> inside the Box
101    }
102}
103
104/// Implements equality comparison based on the agent's unique ID (`Ern`).
105impl PartialEq for AgentHandle {
106    fn eq(&self, other: &Self) -> bool {
107        self.id == other.id
108    }
109}
110
111/// Derives `Eq` based on the `PartialEq` implementation.
112impl Eq for AgentHandle {}
113
114/// Implements hashing based on the agent's unique ID (`Ern`).
115impl Hash for AgentHandle {
116    fn hash<H: Hasher>(&self, state: &mut H) {
117        self.id.hash(state);
118    }
119}
120
121impl AgentHandle {
122    /// Starts a child agent and registers it under this agent's supervision.
123    ///
124    /// This method takes a `ManagedAgent` configured in the [`Idle`] state,
125    /// starts its execution by calling its `start` method, and then stores
126    /// the resulting child `AgentHandle` in this parent handle's `children` map.
127    ///
128    /// # Type Parameters
129    ///
130    /// *   `State`: The user-defined state type of the child agent. Must implement
131    ///     `Default`, `Send`, `Debug`, and be `'static`.
132    ///
133    /// # Arguments
134    ///
135    /// *   `child`: The [`ManagedAgent<Idle, State>`] instance representing the child agent
136    ///     to be started and supervised.
137    ///
138    /// # Returns
139    ///
140    /// A `Result` containing:
141    /// *   `Ok(AgentHandle)`: The handle of the successfully started and registered child agent.
142    /// *   `Err(anyhow::Error)`: If starting the child agent fails.
143    #[instrument(skip(self, child))] // Skip child in instrument
144    pub async fn supervise<State: Default + Send + Debug + 'static>(
145        // Add 'static bound
146        &self,
147        child: ManagedAgent<Idle, State>,
148    ) -> anyhow::Result<AgentHandle> {
149        let child_id = child.id().clone(); // Get ID before consuming child
150        trace!("Supervising child agent with id: {}", child_id);
151        let handle = child.start().await; // Start the child agent
152        trace!(
153            "Child agent {} started, adding to parent {} children map",
154            child_id,
155            self.id
156        );
157        self.children.insert(handle.id.to_string(), handle.clone()); // Store child handle
158        Ok(handle)
159    }
160}
161
162/// Implements the `Broker` trait, allowing broadcasting via the associated broker.
163impl Broker for AgentHandle {
164    /// Sends a message to the associated system broker for broadcasting.
165    ///
166    /// This method wraps the provided `message` in a [`BrokerRequest`] and sends it
167    /// to the broker handle stored within this `AgentHandle`. If no broker handle
168    /// is configured, an error is logged.
169    ///
170    /// # Arguments
171    ///
172    /// * `message`: The message payload (must implement `ActonMessage`) to be broadcast.
173    fn broadcast(&self, message: impl ActonMessage) -> impl Future<Output = ()> + Send + Sync + '_ {
174        trace!("Attempting broadcast via handle: {}", self.id);
175        async move {
176            if let Some(broker_handle) = self.broker.as_ref() {
177                trace!("Broker found for handle {}, sending BrokerRequest", self.id);
178                // Send the BrokerRequest to the actual broker agent.
179                broker_handle.send(BrokerRequest::new(message)).await;
180            } else {
181                // Log an error if no broker is configured for this agent handle.
182                error!(
183                    "No broker configured for agent handle {}, cannot broadcast.",
184                    self.id
185                );
186            }
187        }
188    }
189}
190
191/// Implements the core interface for interacting with an agent.
192#[async_trait]
193impl AgentHandleInterface for AgentHandle {
194    /// Returns the [`MessageAddress`] for this agent, used for sending replies.
195    #[inline]
196    fn reply_address(&self) -> MessageAddress {
197        MessageAddress::new(self.outbox.clone(), self.id.clone())
198    }
199
200    /// Creates an [`OutboundEnvelope`] for sending a message from this agent.
201    ///
202    /// # Arguments
203    ///
204    /// * `recipient_address`: An optional [`MessageAddress`] specifying the recipient.
205    ///   If `None`, the envelope is created without a specific recipient (e.g., for broadcasting
206    ///   or when the recipient is set later).
207    ///
208    /// # Returns
209    ///
210    /// An [`OutboundEnvelope`] with the `return_address` set to this agent's address.
211    #[instrument(skip(self))]
212    fn create_envelope(&self, recipient_address: Option<MessageAddress>) -> OutboundEnvelope {
213        let return_address = self.reply_address();
214        trace!(sender = %return_address.sender.root, recipient = ?recipient_address.as_ref().map(|r| r.sender.root.as_str()), "Creating envelope");
215        if let Some(recipient) = recipient_address {
216            OutboundEnvelope::new_with_recipient(
217                return_address,
218                recipient,
219                self.cancellation_token.clone(),
220            )
221        } else {
222            OutboundEnvelope::new(return_address, self.cancellation_token.clone())
223        }
224    }
225
226    /// Returns a clone of the internal map containing handles to the agent's direct children.
227    ///
228    /// Provides a snapshot of the currently supervised children. Modifications to the
229    /// returned map will not affect the agent's actual children list.
230    #[inline]
231    fn children(&self) -> DashMap<String, AgentHandle> {
232        self.children.clone()
233    }
234
235    /// Searches for a direct child agent by its unique identifier (`Ern`).
236    ///
237    /// # Arguments
238    ///
239    /// * `ern`: The [`Ern`] of the child agent to find.
240    ///
241    /// # Returns
242    ///
243    /// * `Some(AgentHandle)`: If a direct child with the matching `Ern` is found.
244    /// * `None`: If no direct child with the specified `Ern` exists.
245    #[instrument(skip(self))]
246    fn find_child(&self, ern: &Ern) -> Option<AgentHandle> {
247        trace!("Searching for child with ERN: {}", ern);
248        // Access the DashMap using the ERN's string representation as the key.
249        self.children.get(&ern.to_string()).map(
250            |entry| entry.value().clone(), // Clone the handle if found
251        )
252    }
253
254    /// Returns a clone of the agent's task tracker.
255    ///
256    /// The tracker can be used to monitor the agent's main task.
257    #[inline]
258    fn tracker(&self) -> TaskTracker {
259        self.tracker.clone()
260    }
261
262    /// Returns a clone of the agent's unique Entity Resource Name (`Ern`).
263    #[inline]
264    fn id(&self) -> Ern {
265        self.id.clone()
266    }
267
268    /// Returns the agent's root name (the first part of its `Ern`) as a String.
269    #[inline]
270    fn name(&self) -> String {
271        self.id.root.to_string()
272    }
273
274    /// Returns a clone of this `AgentHandle`.
275    #[inline]
276    fn clone_ref(&self) -> AgentHandle {
277        self.clone()
278    }
279
280    /// Sends a [`SystemSignal::Terminate`] message to the agent and waits for its task to complete.
281    ///
282    /// This initiates a graceful shutdown of the agent. It sends the `Terminate` signal
283    /// to the agent's inbox and then waits on the agent's `TaskTracker` until the main
284    /// task (and potentially associated tasks) have finished execution.
285    ///
286    /// The agent's `wake` loop is responsible for handling the `Terminate` signal,
287    /// potentially running `before_stop` and `after_stop` hooks, and stopping child agents.
288    ///
289    /// # Returns
290    ///
291    /// An `anyhow::Result<()>` indicating success or failure. Failure typically occurs
292    /// if sending the `Terminate` signal to the agent's inbox fails (e.g., if the channel
293    /// is already closed).
294    #[allow(clippy::manual_async_fn)] // Keep async_trait style
295    #[instrument(skip(self))]
296    fn stop(&self) -> impl Future<Output = anyhow::Result<()>> + Send + Sync + '_ {
297        async move {
298            let tracker = self.tracker();
299
300            // Create an envelope to send the signal from self to self.
301            let self_envelope = self.create_envelope(Some(self.reply_address()));
302
303            trace!(actor = %self.id, "Sending Terminate signal");
304            // Send the Terminate signal to initiate graceful shutdown.
305            self_envelope.send(SystemSignal::Terminate).await;
306
307            // Wait for the agent's main task and any tracked tasks to finish.
308            tracker.wait().await;
309
310            trace!(actor = %self.id, "Agent terminated successfully.");
311            Ok(())
312        }
313    }
314}