Skip to main content

a2a_rs/port/
message_handler.rs

1//! Message handling port definitions
2
3use async_trait::async_trait;
4
5use crate::domain::{A2AError, Message, Task};
6
7#[async_trait]
8/// An async trait for handling message processing operations
9pub trait AsyncMessageHandler: Send + Sync {
10    /// Process a message for a specific task
11    async fn process_message(
12        &self,
13        task_id: &str,
14        message: &Message,
15        session_id: Option<&str>,
16    ) -> Result<Task, A2AError>;
17
18    /// Validate a message before processing
19    async fn validate_message(&self, message: &Message) -> Result<(), A2AError> {
20        // Default implementation - can be overridden
21        if message.parts.is_empty() {
22            return Err(A2AError::ValidationError {
23                field: "message.parts".to_string(),
24                message: "Message must contain at least one part".to_string(),
25            });
26        }
27        Ok(())
28    }
29
30    /// Transform a message before processing (e.g., for content filtering)
31    async fn transform_message(&self, message: Message) -> Result<Message, A2AError> {
32        // Default implementation - pass through unchanged
33        Ok(message)
34    }
35
36    /// Handle message processing with validation and transformation
37    async fn handle_message_flow(
38        &self,
39        task_id: &str,
40        message: Message,
41        session_id: Option<&str>,
42    ) -> Result<Task, A2AError> {
43        // Validate the message
44        self.validate_message(&message).await?;
45
46        // Transform the message if needed
47        let transformed_message = self.transform_message(message).await?;
48
49        // Process the message
50        self.process_message(task_id, &transformed_message, session_id)
51            .await
52    }
53}