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 let (outbox, _) = mpsc::channel(1); // Create a dummy channel
79 AgentHandle {
80 id: Ern::default(),
81 outbox,
82 tracker: TaskTracker::new(),
83 parent: None,
84 broker: Box::new(None),
85 children: DashMap::new(),
86 cancellation_token: tokio_util::sync::CancellationToken::new(),
87 }
88 }
89}
90
91/// Implements the `Subscriber` trait, allowing access to the broker.
92impl Subscriber for AgentHandle {
93 /// Returns a clone of the optional broker handle associated with this agent.
94 ///
95 /// Returns `None` if the agent was not configured with a broker reference.
96 fn get_broker(&self) -> Option<BrokerRef> {
97 *self.broker.clone() // Clone the Option<BrokerRef> inside the Box
98 }
99}
100
101/// Implements equality comparison based on the agent's unique ID (`Ern`).
102impl PartialEq for AgentHandle {
103 fn eq(&self, other: &Self) -> bool {
104 self.id == other.id
105 }
106}
107
108/// Derives `Eq` based on the `PartialEq` implementation.
109impl Eq for AgentHandle {}
110
111/// Implements hashing based on the agent's unique ID (`Ern`).
112impl Hash for AgentHandle {
113 fn hash<H: Hasher>(&self, state: &mut H) {
114 self.id.hash(state);
115 }
116}
117
118impl AgentHandle {
119 /// Starts a child agent and registers it under this agent's supervision.
120 ///
121 /// This method takes a `ManagedAgent` configured in the [`Idle`] state,
122 /// starts its execution by calling its `start` method, and then stores
123 /// the resulting child `AgentHandle` in this parent handle's `children` map.
124 ///
125 /// # Type Parameters
126 ///
127 /// * `State`: The user-defined state type of the child agent. Must implement
128 /// `Default`, `Send`, `Debug`, and be `'static`.
129 ///
130 /// # Arguments
131 ///
132 /// * `child`: The [`ManagedAgent<Idle, State>`] instance representing the child agent
133 /// to be started and supervised.
134 ///
135 /// # Returns
136 ///
137 /// A `Result` containing:
138 /// * `Ok(AgentHandle)`: The handle of the successfully started and registered child agent.
139 /// * `Err(anyhow::Error)`: If starting the child agent fails.
140 #[instrument(skip(self, child))] // Skip child in instrument
141 pub async fn supervise<State: Default + Send + Debug + 'static>(
142 // Add 'static bound
143 &self,
144 child: ManagedAgent<Idle, State>,
145 ) -> anyhow::Result<AgentHandle> {
146 let child_id = child.id().clone(); // Get ID before consuming child
147 trace!("Supervising child agent with id: {}", child_id);
148 let handle = child.start().await; // Start the child agent
149 trace!(
150 "Child agent {} started, adding to parent {} children map",
151 child_id,
152 self.id
153 );
154 self.children.insert(handle.id.to_string(), handle.clone()); // Store child handle
155 Ok(handle)
156 }
157}
158
159/// Implements the `Broker` trait, allowing broadcasting via the associated broker.
160impl Broker for AgentHandle {
161 /// Sends a message to the associated system broker for broadcasting.
162 ///
163 /// This method wraps the provided `message` in a [`BrokerRequest`] and sends it
164 /// to the broker handle stored within this `AgentHandle`. If no broker handle
165 /// is configured, an error is logged.
166 ///
167 /// # Arguments
168 ///
169 /// * `message`: The message payload (must implement `ActonMessage`) to be broadcast.
170 fn broadcast(&self, message: impl ActonMessage) -> impl Future<Output = ()> + Send + Sync + '_ {
171 trace!("Attempting broadcast via handle: {}", self.id);
172 async move {
173 if let Some(broker_handle) = self.broker.as_ref() {
174 trace!("Broker found for handle {}, sending BrokerRequest", self.id);
175 // Send the BrokerRequest to the actual broker agent.
176 broker_handle.send(BrokerRequest::new(message)).await;
177 } else {
178 // Log an error if no broker is configured for this agent handle.
179 error!(
180 "No broker configured for agent handle {}, cannot broadcast.",
181 self.id
182 );
183 }
184 }
185 }
186}
187
188/// Implements the core interface for interacting with an agent.
189#[async_trait]
190impl AgentHandleInterface for AgentHandle {
191 /// Returns the [`MessageAddress`] for this agent, used for sending replies.
192 #[inline]
193 fn reply_address(&self) -> MessageAddress {
194 MessageAddress::new(self.outbox.clone(), self.id.clone())
195 }
196
197 /// Creates an [`OutboundEnvelope`] for sending a message from this agent.
198 ///
199 /// # Arguments
200 ///
201 /// * `recipient_address`: An optional [`MessageAddress`] specifying the recipient.
202 /// If `None`, the envelope is created without a specific recipient (e.g., for broadcasting
203 /// or when the recipient is set later).
204 ///
205 /// # Returns
206 ///
207 /// An [`OutboundEnvelope`] with the `return_address` set to this agent's address.
208 #[instrument(skip(self))]
209 fn create_envelope(&self, recipient_address: Option<MessageAddress>) -> OutboundEnvelope {
210 let return_address = self.reply_address();
211 trace!(sender = %return_address.sender.root, recipient = ?recipient_address.as_ref().map(|r| r.sender.root.as_str()), "Creating envelope");
212 if let Some(recipient) = recipient_address {
213 OutboundEnvelope::new_with_recipient(
214 return_address,
215 recipient,
216 self.cancellation_token.clone(),
217 )
218 } else {
219 OutboundEnvelope::new(return_address, self.cancellation_token.clone())
220 }
221 }
222
223 /// Returns a clone of the internal map containing handles to the agent's direct children.
224 ///
225 /// Provides a snapshot of the currently supervised children. Modifications to the
226 /// returned map will not affect the agent's actual children list.
227 #[inline]
228 fn children(&self) -> DashMap<String, AgentHandle> {
229 self.children.clone()
230 }
231
232 /// Searches for a direct child agent by its unique identifier (`Ern`).
233 ///
234 /// # Arguments
235 ///
236 /// * `ern`: The [`Ern`] of the child agent to find.
237 ///
238 /// # Returns
239 ///
240 /// * `Some(AgentHandle)`: If a direct child with the matching `Ern` is found.
241 /// * `None`: If no direct child with the specified `Ern` exists.
242 #[instrument(skip(self))]
243 fn find_child(&self, ern: &Ern) -> Option<AgentHandle> {
244 trace!("Searching for child with ERN: {}", ern);
245 // Access the DashMap using the ERN's string representation as the key.
246 self.children.get(&ern.to_string()).map(
247 |entry| entry.value().clone(), // Clone the handle if found
248 )
249 }
250
251 /// Returns a clone of the agent's task tracker.
252 ///
253 /// The tracker can be used to monitor the agent's main task.
254 #[inline]
255 fn tracker(&self) -> TaskTracker {
256 self.tracker.clone()
257 }
258
259 /// Returns a clone of the agent's unique Entity Resource Name (`Ern`).
260 #[inline]
261 fn id(&self) -> Ern {
262 self.id.clone()
263 }
264
265 /// Returns the agent's root name (the first part of its `Ern`) as a String.
266 #[inline]
267 fn name(&self) -> String {
268 self.id.root.to_string()
269 }
270
271 /// Returns a clone of this `AgentHandle`.
272 #[inline]
273 fn clone_ref(&self) -> AgentHandle {
274 self.clone()
275 }
276
277 /// Sends a [`SystemSignal::Terminate`] message to the agent and waits for its task to complete.
278 ///
279 /// This initiates a graceful shutdown of the agent. It sends the `Terminate` signal
280 /// to the agent's inbox and then waits on the agent's `TaskTracker` until the main
281 /// task (and potentially associated tasks) have finished execution.
282 ///
283 /// The agent's `wake` loop is responsible for handling the `Terminate` signal,
284 /// potentially running `before_stop` and `after_stop` hooks, and stopping child agents.
285 ///
286 /// # Returns
287 ///
288 /// An `anyhow::Result<()>` indicating success or failure. Failure typically occurs
289 /// if sending the `Terminate` signal to the agent's inbox fails (e.g., if the channel
290 /// is already closed).
291 #[allow(clippy::manual_async_fn)] // Keep async_trait style
292 #[instrument(skip(self))]
293 fn stop(&self) -> impl Future<Output = anyhow::Result<()>> + Send + Sync + '_ {
294 async move {
295 let tracker = self.tracker();
296
297 // Create an envelope to send the signal from self to self.
298 let self_envelope = self.create_envelope(Some(self.reply_address()));
299
300 trace!(actor = %self.id, "Sending Terminate signal");
301 // Send the Terminate signal to initiate graceful shutdown.
302 self_envelope.send(SystemSignal::Terminate).await;
303
304 // Wait for the agent's main task and any tracked tasks to finish.
305 tracker.wait().await;
306
307 trace!(actor = %self.id, "Agent terminated successfully.");
308 Ok(())
309 }
310 }
311}