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 std::env;
24use std::time::Duration;
25use tokio::sync::mpsc;
26use tokio::time::timeout as tokio_timeout;
27use tokio_util::task::TaskTracker;
28use tracing::{error, instrument, trace, warn}; // warn seems unused
29
30use crate::actor::{Idle, ManagedAgent};
31use crate::common::{AgentSender, BrokerRef, OutboundEnvelope, ParentRef};
32use crate::message::{BrokerRequest, MessageAddress, SystemSignal};
33use crate::prelude::ActonMessage;
34use crate::traits::{AgentHandleInterface, Broker, Subscriber};
35
36/// A clonable handle for interacting with an agent.
37///
38/// `AgentHandle` provides the primary mechanism for communicating with and managing
39/// an agent from outside its own execution context. It encapsulates the necessary
40/// information to send messages to the agent's inbox (`outbox`), identify the agent (`id`),
41/// manage its lifecycle (`stop`), track its tasks (`tracker`), and navigate the
42/// supervision hierarchy (`parent`, `children`, `supervise`).
43///
44/// Handles can be cloned freely, allowing multiple parts of the system to hold references
45/// to the same agent. Sending messages through the handle is asynchronous.
46///
47/// Key functionalities are exposed through implemented traits:
48/// * [`AgentHandleInterface`]: Core methods for interaction (sending messages, stopping, etc.).
49/// * [`Broker`]: Methods for broadcasting messages via the system broker.
50/// * [`Subscriber`]: Method for accessing the system broker handle.
51///
52/// Equality and hashing are based solely on the agent's unique identifier (`id`).
53#[derive(Debug, Clone)]
54pub struct AgentHandle {
55 /// The unique identifier (`Ern`) for the agent this handle refers to.
56 pub(crate) id: Ern,
57 /// The sender part of the MPSC channel connected to the agent's inbox.
58 pub(crate) outbox: AgentSender,
59 /// Tracks the agent's main task and potentially other associated tasks.
60 tracker: TaskTracker,
61 /// Optional reference to the parent (supervisor) agent's handle.
62 /// `None` if this is a top-level agent. Boxed to manage `AgentHandle` size.
63 pub parent: Option<Box<ParentRef>>,
64 /// Optional reference to the system message broker's handle.
65 /// Boxed to manage `AgentHandle` size.
66 pub broker: Box<Option<BrokerRef>>,
67 /// A map holding handles to the direct children supervised by this agent.
68 /// Keys are the string representation of the child agent's `Ern`.
69 children: DashMap<String, AgentHandle>,
70}
71
72impl Default for AgentHandle {
73 /// Creates a default, placeholder `AgentHandle`.
74 ///
75 /// This handle is typically initialized with a default `Ern`, a closed channel,
76 /// and no parent, broker, or children. It's primarily used as a starting point
77 /// before being properly configured when a `ManagedAgent` is created.
78 fn default() -> Self {
79 let (outbox, _) = mpsc::channel(1); // Create a dummy channel
80 AgentHandle {
81 id: Ern::default(),
82 outbox,
83 tracker: TaskTracker::new(),
84 parent: None,
85 broker: Box::new(None),
86 children: DashMap::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(return_address, recipient)
214 } else {
215 OutboundEnvelope::new(return_address)
216 }
217 }
218
219 /// Returns a clone of the internal map containing handles to the agent's direct children.
220 ///
221 /// Provides a snapshot of the currently supervised children. Modifications to the
222 /// returned map will not affect the agent's actual children list.
223 #[inline]
224 fn children(&self) -> DashMap<String, AgentHandle> {
225 self.children.clone()
226 }
227
228 /// Searches for a direct child agent by its unique identifier (`Ern`).
229 ///
230 /// # Arguments
231 ///
232 /// * `ern`: The [`Ern`] of the child agent to find.
233 ///
234 /// # Returns
235 ///
236 /// * `Some(AgentHandle)`: If a direct child with the matching `Ern` is found.
237 /// * `None`: If no direct child with the specified `Ern` exists.
238 #[instrument(skip(self))]
239 fn find_child(&self, ern: &Ern) -> Option<AgentHandle> {
240 trace!("Searching for child with ERN: {}", ern);
241 // Access the DashMap using the ERN's string representation as the key.
242 self.children.get(&ern.to_string()).map(
243 |entry| entry.value().clone(), // Clone the handle if found
244 )
245 }
246
247 /// Returns a clone of the agent's task tracker.
248 ///
249 /// The tracker can be used to monitor the agent's main task.
250 #[inline]
251 fn tracker(&self) -> TaskTracker {
252 self.tracker.clone()
253 }
254
255 /// Returns a clone of the agent's unique Entity Resource Name (`Ern`).
256 #[inline]
257 fn id(&self) -> Ern {
258 self.id.clone()
259 }
260
261 /// Returns the agent's root name (the first part of its `Ern`) as a String.
262 #[inline]
263 fn name(&self) -> String {
264 self.id.root.to_string()
265 }
266
267 /// Returns a clone of this `AgentHandle`.
268 #[inline]
269 fn clone_ref(&self) -> AgentHandle {
270 self.clone()
271 }
272
273 /// Sends a [`SystemSignal::Terminate`] message to the agent and waits for its task to complete.
274 ///
275 /// This initiates a graceful shutdown of the agent. It sends the `Terminate` signal
276 /// to the agent's inbox and then waits on the agent's `TaskTracker` until the main
277 /// task (and potentially associated tasks) have finished execution.
278 ///
279 /// The agent's `wake` loop is responsible for handling the `Terminate` signal,
280 /// potentially running `before_stop` and `after_stop` hooks, and stopping child agents.
281 ///
282 /// # Returns
283 ///
284 /// An `anyhow::Result<()>` indicating success or failure. Failure typically occurs
285 /// if sending the `Terminate` signal to the agent's inbox fails (e.g., if the channel
286 /// is already closed).
287 #[allow(clippy::manual_async_fn)] // Keep async_trait style
288 #[instrument(skip(self))]
289 fn stop(&self) -> impl Future<Output = anyhow::Result<()>> + Send + Sync + '_ {
290 async move {
291 let tracker = self.tracker();
292 // Create an envelope to send the signal from self to self.
293 let self_envelope = self.create_envelope(Some(self.reply_address()));
294
295 trace!(actor = %self.id, "Sending Terminate signal");
296 // Send the Terminate signal. Use `?` to propagate potential send errors.
297 //self_envelope.reply(SystemSignal::Terminate)?;
298 self_envelope.send(SystemSignal::Terminate).await;
299 // Determine agent shutdown timeout from env or use default (10s)
300 let timeout_ms: u64 = env::var("ACTON_AGENT_SHUTDOWN_TIMEOUT_MS")
301 .ok()
302 .and_then(|val| val.parse().ok())
303 .unwrap_or(10_000);
304
305 trace!(actor = %self.id, timeout_ms, "Waiting for agent tasks to complete...");
306
307 // Wait for the agent's main task and any tracked tasks to finish, within timeout.
308 let wait_fut = tracker.wait();
309 match tokio_timeout(Duration::from_millis(timeout_ms), wait_fut).await {
310 Ok(()) => {
311 trace!(actor = %self.id, "Agent terminated successfully.");
312 Ok(())
313 }
314 Err(_) => {
315 error!(
316 "Shutdown timeout for agent {} after {} ms",
317 self.id, timeout_ms
318 );
319 Err(anyhow::anyhow!(
320 "Timeout while waiting for agent {} to shut down",
321 self.id
322 ))
323 }
324 }
325 }
326 }
327}