mojentic 3.0.1

An LLM integration framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Async event aggregator agent implementation.
//!
//! This module provides an agent that aggregates events by correlation ID,
//! waiting for all required event types before processing them together.

use crate::agents::BaseAsyncAgent;
use crate::event::Event;
use crate::{MojenticError, Result};
use async_trait::async_trait;
use std::any::TypeId;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{oneshot, Mutex};
use tracing::debug;

type EventStore = Arc<Mutex<HashMap<String, Vec<Box<dyn Event>>>>>;
type WaiterStore = Arc<Mutex<HashMap<String, Vec<oneshot::Sender<Vec<Box<dyn Event>>>>>>>;

/// An agent that aggregates events by correlation ID.
///
/// This agent waits for all specified event types to arrive for a given
/// correlation ID before processing them together. This is useful for
/// workflows where multiple independent operations must complete before
/// a final action can be taken.
///
/// # Examples
///
/// ```ignore
/// use mojentic::agents::AsyncAggregatorAgent;
/// use std::any::TypeId;
///
/// let agent = AsyncAggregatorAgent::new(vec![
///     TypeId::of::<Event1>(),
///     TypeId::of::<Event2>(),
/// ]);
/// ```
pub struct AsyncAggregatorAgent {
    event_types_needed: Vec<TypeId>,
    results: EventStore,
    waiters: WaiterStore,
}

impl AsyncAggregatorAgent {
    /// Create a new AsyncAggregatorAgent.
    ///
    /// # Arguments
    ///
    /// * `event_types_needed` - Vector of TypeIds representing the event types
    ///   that must be collected before processing
    pub fn new(event_types_needed: Vec<TypeId>) -> Self {
        Self {
            event_types_needed,
            results: Arc::new(Mutex::new(HashMap::new())),
            waiters: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// Wait for all needed events for a specific correlation ID.
    ///
    /// This method blocks until all required event types have been received
    /// for the given correlation ID, or until the timeout expires.
    ///
    /// # Arguments
    ///
    /// * `correlation_id` - The correlation ID to wait for
    /// * `timeout` - Optional timeout duration
    ///
    /// # Returns
    ///
    /// Vector of all events collected for this correlation ID
    pub async fn wait_for_events(
        &self,
        correlation_id: &str,
        timeout: Option<Duration>,
    ) -> Result<Vec<Box<dyn Event>>> {
        // Check if we already have all needed events
        {
            let results = self.results.lock().await;
            if let Some(events) = results.get(correlation_id) {
                if self.has_all_needed_types(events) {
                    debug!(
                        "All needed events already available for correlation_id: {}",
                        correlation_id
                    );
                    return Ok(events.iter().map(|e| e.clone_box()).collect());
                }
            }
        }

        // Create a oneshot channel to wait for events
        let (tx, rx) = oneshot::channel();

        // Register the waiter
        {
            let mut waiters = self.waiters.lock().await;
            waiters.entry(correlation_id.to_string()).or_default().push(tx);
        }

        // Wait for the events with optional timeout
        if let Some(timeout_duration) = timeout {
            match tokio::time::timeout(timeout_duration, rx).await {
                Ok(Ok(events)) => Ok(events),
                Ok(Err(_)) => Err(MojenticError::EventError(
                    "Channel closed before events arrived".to_string(),
                )),
                Err(_) => {
                    debug!("Timeout waiting for events for correlation_id: {}", correlation_id);
                    // Return whatever we have collected so far
                    Err(MojenticError::TimeoutError(format!(
                        "Timeout waiting for events for correlation_id: {}",
                        correlation_id
                    )))
                }
            }
        } else {
            rx.await.map_err(|_| {
                MojenticError::EventError("Channel closed before events arrived".to_string())
            })
        }
    }

    /// Process collected events.
    ///
    /// This method is called when all needed event types have been collected.
    /// Override this in subclasses to implement custom processing logic.
    ///
    /// # Arguments
    ///
    /// * `events` - All collected events for a correlation ID
    ///
    /// # Returns
    ///
    /// Vector of new events to emit
    pub async fn process_events(
        &self,
        _events: Vec<Box<dyn Event>>,
    ) -> Result<Vec<Box<dyn Event>>> {
        // Default implementation returns empty
        // Subclasses should override this
        Ok(vec![])
    }

    /// Check if we have all needed event types.
    fn has_all_needed_types(&self, events: &[Box<dyn Event>]) -> bool {
        let event_types: Vec<TypeId> = events.iter().map(|e| e.as_any().type_id()).collect();

        self.event_types_needed
            .iter()
            .all(|needed_type| event_types.contains(needed_type))
    }

    /// Capture an event and check if we have all needed types.
    async fn capture_event(&self, event: Box<dyn Event>) -> Result<Option<Vec<Box<dyn Event>>>> {
        let correlation_id = event
            .correlation_id()
            .ok_or_else(|| MojenticError::EventError("Event missing correlation_id".to_string()))?
            .to_string();

        // Add event to results
        {
            let mut results = self.results.lock().await;
            results.entry(correlation_id.clone()).or_default().push(event);
        }

        // Check if we have all needed events
        let all_events: Option<Vec<Box<dyn Event>>> = {
            let results = self.results.lock().await;
            results
                .get(&correlation_id)
                .map(|events| events.iter().map(|e| e.clone_box()).collect())
        };

        if let Some(events) = all_events {
            if self.has_all_needed_types(&events) {
                debug!("All needed events collected for correlation_id: {}", correlation_id);

                // Notify all waiters
                {
                    let mut waiters = self.waiters.lock().await;
                    if let Some(senders) = waiters.remove(&correlation_id) {
                        for sender in senders {
                            let events_for_waiter: Vec<Box<dyn Event>> =
                                events.iter().map(|e| e.clone_box()).collect();
                            let _ = sender.send(events_for_waiter);
                        }
                    }
                }

                // Clear results for this correlation_id
                {
                    let mut results = self.results.lock().await;
                    results.remove(&correlation_id);
                }

                return Ok(Some(events));
            }
        }

        Ok(None)
    }
}

#[async_trait]
impl BaseAsyncAgent for AsyncAggregatorAgent {
    async fn receive_event_async(&self, event: Box<dyn Event>) -> Result<Vec<Box<dyn Event>>> {
        debug!("AsyncAggregatorAgent received event");

        // Capture the event
        if let Some(events) = self.capture_event(event).await? {
            // We have all needed events, process them
            return self.process_events(events).await;
        }

        // Still waiting for more events
        Ok(vec![])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};
    use std::any::Any;

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct Event1 {
        source: String,
        correlation_id: Option<String>,
        data: String,
    }

    impl Event for Event1 {
        fn source(&self) -> &str {
            &self.source
        }
        fn correlation_id(&self) -> Option<&str> {
            self.correlation_id.as_deref()
        }
        fn set_correlation_id(&mut self, id: String) {
            self.correlation_id = Some(id);
        }
        fn as_any(&self) -> &dyn Any {
            self
        }
        fn clone_box(&self) -> Box<dyn Event> {
            Box::new(self.clone())
        }
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct Event2 {
        source: String,
        correlation_id: Option<String>,
        value: i32,
    }

    impl Event for Event2 {
        fn source(&self) -> &str {
            &self.source
        }
        fn correlation_id(&self) -> Option<&str> {
            self.correlation_id.as_deref()
        }
        fn set_correlation_id(&mut self, id: String) {
            self.correlation_id = Some(id);
        }
        fn as_any(&self) -> &dyn Any {
            self
        }
        fn clone_box(&self) -> Box<dyn Event> {
            Box::new(self.clone())
        }
    }

    #[tokio::test]
    async fn test_new_aggregator() {
        let agent = AsyncAggregatorAgent::new(vec![TypeId::of::<Event1>(), TypeId::of::<Event2>()]);
        assert_eq!(agent.event_types_needed.len(), 2);
    }

    #[tokio::test]
    async fn test_single_event_does_not_trigger() {
        let agent = AsyncAggregatorAgent::new(vec![TypeId::of::<Event1>(), TypeId::of::<Event2>()]);

        let event1 = Box::new(Event1 {
            source: "Test".to_string(),
            correlation_id: Some("test-123".to_string()),
            data: "data".to_string(),
        }) as Box<dyn Event>;

        let result = agent.receive_event_async(event1).await.unwrap();
        assert_eq!(result.len(), 0); // Should not process yet
    }

    #[tokio::test]
    async fn test_both_events_trigger_processing() {
        let agent = Arc::new(AsyncAggregatorAgent::new(vec![
            TypeId::of::<Event1>(),
            TypeId::of::<Event2>(),
        ]));

        let event1 = Box::new(Event1 {
            source: "Test".to_string(),
            correlation_id: Some("test-123".to_string()),
            data: "data".to_string(),
        }) as Box<dyn Event>;

        let event2 = Box::new(Event2 {
            source: "Test".to_string(),
            correlation_id: Some("test-123".to_string()),
            value: 42,
        }) as Box<dyn Event>;

        // First event should not trigger
        let result1 = agent.receive_event_async(event1).await.unwrap();
        assert_eq!(result1.len(), 0);

        // Second event should trigger processing
        let result2 = agent.receive_event_async(event2).await.unwrap();
        // Default process_events returns empty, but it should have been called
        assert_eq!(result2.len(), 0);
    }

    #[tokio::test]
    async fn test_wait_for_events() {
        let agent = Arc::new(AsyncAggregatorAgent::new(vec![
            TypeId::of::<Event1>(),
            TypeId::of::<Event2>(),
        ]));

        let correlation_id = "wait-test-456";
        let agent_clone = agent.clone();

        // Spawn a task that will send events
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(100)).await;

            let event1 = Box::new(Event1 {
                source: "Test".to_string(),
                correlation_id: Some(correlation_id.to_string()),
                data: "data".to_string(),
            }) as Box<dyn Event>;

            agent_clone.receive_event_async(event1).await.unwrap();

            tokio::time::sleep(Duration::from_millis(100)).await;

            let event2 = Box::new(Event2 {
                source: "Test".to_string(),
                correlation_id: Some(correlation_id.to_string()),
                value: 42,
            }) as Box<dyn Event>;

            agent_clone.receive_event_async(event2).await.unwrap();
        });

        // Wait for all events
        let result = agent
            .wait_for_events(correlation_id, Some(Duration::from_secs(5)))
            .await
            .unwrap();

        assert_eq!(result.len(), 2);
    }

    #[tokio::test]
    async fn test_wait_for_events_timeout() {
        let agent = AsyncAggregatorAgent::new(vec![TypeId::of::<Event1>(), TypeId::of::<Event2>()]);

        // Send only one event
        let event1 = Box::new(Event1 {
            source: "Test".to_string(),
            correlation_id: Some("timeout-test".to_string()),
            data: "data".to_string(),
        }) as Box<dyn Event>;

        agent.receive_event_async(event1).await.unwrap();

        // Wait should timeout
        let result = agent.wait_for_events("timeout-test", Some(Duration::from_millis(100))).await;

        assert!(result.is_err());
        match result {
            Err(MojenticError::TimeoutError(_)) => {}
            _ => panic!("Expected TimeoutError"),
        }
    }

    #[tokio::test]
    async fn test_different_correlation_ids() {
        let agent = Arc::new(AsyncAggregatorAgent::new(vec![
            TypeId::of::<Event1>(),
            TypeId::of::<Event2>(),
        ]));

        // Send events with different correlation IDs
        let event1_a = Box::new(Event1 {
            source: "Test".to_string(),
            correlation_id: Some("corr-a".to_string()),
            data: "data-a".to_string(),
        }) as Box<dyn Event>;

        let event1_b = Box::new(Event1 {
            source: "Test".to_string(),
            correlation_id: Some("corr-b".to_string()),
            data: "data-b".to_string(),
        }) as Box<dyn Event>;

        agent.receive_event_async(event1_a).await.unwrap();
        agent.receive_event_async(event1_b).await.unwrap();

        // Complete corr-a
        let event2_a = Box::new(Event2 {
            source: "Test".to_string(),
            correlation_id: Some("corr-a".to_string()),
            value: 1,
        }) as Box<dyn Event>;

        let result = agent.receive_event_async(event2_a).await.unwrap();
        assert_eq!(result.len(), 0); // corr-a completes

        // Complete corr-b
        let event2_b = Box::new(Event2 {
            source: "Test".to_string(),
            correlation_id: Some("corr-b".to_string()),
            value: 2,
        }) as Box<dyn Event>;

        let result = agent.receive_event_async(event2_b).await.unwrap();
        assert_eq!(result.len(), 0); // corr-b completes
    }

    #[tokio::test]
    async fn test_event_without_correlation_id_fails() {
        let agent = AsyncAggregatorAgent::new(vec![TypeId::of::<Event1>()]);

        let event = Box::new(Event1 {
            source: "Test".to_string(),
            correlation_id: None,
            data: "data".to_string(),
        }) as Box<dyn Event>;

        let result = agent.receive_event_async(event).await;
        assert!(result.is_err());
        match result {
            Err(MojenticError::EventError(_)) => {}
            _ => panic!("Expected EventError"),
        }
    }

    #[tokio::test]
    async fn test_process_events_override() {
        struct CustomAggregator {
            inner: AsyncAggregatorAgent,
            processed_count: Arc<Mutex<usize>>,
        }

        impl CustomAggregator {
            fn new(event_types: Vec<TypeId>) -> Self {
                Self {
                    inner: AsyncAggregatorAgent::new(event_types),
                    processed_count: Arc::new(Mutex::new(0)),
                }
            }
        }

        #[async_trait]
        impl BaseAsyncAgent for CustomAggregator {
            async fn receive_event_async(
                &self,
                event: Box<dyn Event>,
            ) -> Result<Vec<Box<dyn Event>>> {
                if let Some(_events) = self.inner.capture_event(event).await? {
                    // Custom processing
                    let mut count = self.processed_count.lock().await;
                    *count += 1;

                    return Ok(vec![]);
                }
                Ok(vec![])
            }
        }

        let agent = CustomAggregator::new(vec![TypeId::of::<Event1>(), TypeId::of::<Event2>()]);
        let count_clone = agent.processed_count.clone();

        let event1 = Box::new(Event1 {
            source: "Test".to_string(),
            correlation_id: Some("custom-test".to_string()),
            data: "data".to_string(),
        }) as Box<dyn Event>;

        let event2 = Box::new(Event2 {
            source: "Test".to_string(),
            correlation_id: Some("custom-test".to_string()),
            value: 42,
        }) as Box<dyn Event>;

        agent.receive_event_async(event1).await.unwrap();
        agent.receive_event_async(event2).await.unwrap();

        let count = *count_clone.lock().await;
        assert_eq!(count, 1); // process_events should have been called once
    }
}