terraphim_agent_messaging 1.19.2

Erlang-style asynchronous message passing system for AI agents
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
//! Message types and patterns for agent communication
//!
//! Implements Erlang-style message patterns: call, cast, and info.

use std::any::Any;
use std::time::Duration;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::oneshot;
use uuid::Uuid;

use crate::AgentPid;

/// Unique identifier for messages
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MessageId(pub Uuid);

impl MessageId {
    pub fn new() -> Self {
        Self(Uuid::new_v4())
    }

    pub fn as_str(&self) -> String {
        self.0.to_string()
    }
}

impl Default for MessageId {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Display for MessageId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Message priority levels
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
pub enum MessagePriority {
    Low = 0,
    #[default]
    Normal = 1,
    High = 2,
    Critical = 3,
}

/// Message delivery options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryOptions {
    /// Message priority
    pub priority: MessagePriority,
    /// Timeout for message delivery
    pub timeout: Duration,
    /// Whether to require acknowledgment
    pub require_ack: bool,
    /// Maximum retry attempts
    pub max_retries: u32,
    /// Retry delay
    pub retry_delay: Duration,
}

impl Default for DeliveryOptions {
    fn default() -> Self {
        Self {
            priority: MessagePriority::Normal,
            timeout: Duration::from_secs(30),
            require_ack: false,
            max_retries: 3,
            retry_delay: Duration::from_millis(100),
        }
    }
}

/// Core agent message types following Erlang patterns
#[derive(Debug)]
pub enum AgentMessage {
    /// Synchronous call (gen_server:call) - expects a response
    Call {
        id: MessageId,
        from: AgentPid,
        payload: Box<dyn Any + Send>,
        reply_to: oneshot::Sender<Box<dyn Any + Send>>,
        timeout: Duration,
    },

    /// Asynchronous cast (gen_server:cast) - fire and forget
    Cast {
        id: MessageId,
        from: AgentPid,
        payload: Box<dyn Any + Send>,
    },

    /// System info message (gen_server:info) - system notifications
    Info { id: MessageId, info: SystemInfo },

    /// Response to a call message
    Reply {
        id: MessageId,
        to: AgentPid,
        payload: Box<dyn Any + Send>,
    },

    /// Acknowledgment message
    Ack {
        id: MessageId,
        original_message_id: MessageId,
    },
}

impl AgentMessage {
    /// Get the message ID
    pub fn id(&self) -> &MessageId {
        match self {
            AgentMessage::Call { id, .. } => id,
            AgentMessage::Cast { id, .. } => id,
            AgentMessage::Info { id, .. } => id,
            AgentMessage::Reply { id, .. } => id,
            AgentMessage::Ack { id, .. } => id,
        }
    }

    /// Get the sender (if applicable)
    pub fn from(&self) -> Option<&AgentPid> {
        match self {
            AgentMessage::Call { from, .. } => Some(from),
            AgentMessage::Cast { from, .. } => Some(from),
            AgentMessage::Info { .. } => None,
            AgentMessage::Reply { .. } => None,
            AgentMessage::Ack { .. } => None,
        }
    }

    /// Check if this is a call message that expects a response
    pub fn expects_response(&self) -> bool {
        matches!(self, AgentMessage::Call { .. })
    }

    /// Create a call message
    pub fn call<T>(
        from: AgentPid,
        payload: T,
        timeout: Duration,
    ) -> (Self, oneshot::Receiver<Box<dyn Any + Send>>)
    where
        T: Any + Send + 'static,
    {
        let (reply_tx, reply_rx) = oneshot::channel();
        let message = AgentMessage::Call {
            id: MessageId::new(),
            from,
            payload: Box::new(payload),
            reply_to: reply_tx,
            timeout,
        };
        (message, reply_rx)
    }

    /// Create a cast message
    pub fn cast<T>(from: AgentPid, payload: T) -> Self
    where
        T: Any + Send + 'static,
    {
        AgentMessage::Cast {
            id: MessageId::new(),
            from,
            payload: Box::new(payload),
        }
    }

    /// Create an info message
    pub fn info(info: SystemInfo) -> Self {
        AgentMessage::Info {
            id: MessageId::new(),
            info,
        }
    }

    /// Create a reply message
    pub fn reply<T>(to: AgentPid, payload: T) -> Self
    where
        T: Any + Send + 'static,
    {
        AgentMessage::Reply {
            id: MessageId::new(),
            to,
            payload: Box::new(payload),
        }
    }

    /// Create an acknowledgment message
    pub fn ack(original_message_id: MessageId) -> Self {
        AgentMessage::Ack {
            id: MessageId::new(),
            original_message_id,
        }
    }
}

/// System information messages
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SystemInfo {
    /// Agent started
    AgentStarted {
        agent_id: AgentPid,
        timestamp: DateTime<Utc>,
    },

    /// Agent stopped
    AgentStopped {
        agent_id: AgentPid,
        timestamp: DateTime<Utc>,
        reason: String,
    },

    /// Agent health check
    HealthCheck {
        agent_id: AgentPid,
        timestamp: DateTime<Utc>,
    },

    /// System shutdown
    SystemShutdown {
        timestamp: DateTime<Utc>,
        reason: String,
    },

    /// Custom system message
    Custom {
        message_type: String,
        data: serde_json::Value,
        timestamp: DateTime<Utc>,
    },
}

/// Message envelope for serialization and routing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageEnvelope {
    pub id: MessageId,
    pub from: Option<AgentPid>,
    pub to: AgentPid,
    pub message_type: String,
    pub payload: serde_json::Value,
    pub delivery_options: DeliveryOptions,
    pub created_at: DateTime<Utc>,
    pub attempts: u32,
}

impl MessageEnvelope {
    /// Create a new message envelope
    pub fn new(
        to: AgentPid,
        message_type: String,
        payload: serde_json::Value,
        delivery_options: DeliveryOptions,
    ) -> Self {
        Self {
            id: MessageId::new(),
            from: None,
            to,
            message_type,
            payload,
            delivery_options,
            created_at: Utc::now(),
            attempts: 0,
        }
    }

    /// Set the sender
    pub fn with_from(mut self, from: AgentPid) -> Self {
        self.from = Some(from);
        self
    }

    /// Increment attempt counter
    pub fn increment_attempts(&mut self) {
        self.attempts += 1;
    }

    /// Check if max retries exceeded
    pub fn max_retries_exceeded(&self) -> bool {
        self.attempts >= self.delivery_options.max_retries
    }

    /// Check if message has expired.
    /// The `now` parameter enables deterministic testing of expiry boundaries.
    pub fn is_expired(&self, now: DateTime<Utc>) -> bool {
        let elapsed = now - self.created_at;
        elapsed.to_std().unwrap_or(Duration::ZERO) > self.delivery_options.timeout
    }
}

/// Typed message wrapper for type-safe messaging
pub struct TypedMessage<T> {
    pub id: MessageId,
    pub from: Option<AgentPid>,
    pub payload: T,
    pub created_at: DateTime<Utc>,
}

impl<T> TypedMessage<T> {
    pub fn new(payload: T) -> Self {
        Self {
            id: MessageId::new(),
            from: None,
            payload,
            created_at: Utc::now(),
        }
    }

    pub fn with_from(mut self, from: AgentPid) -> Self {
        self.from = Some(from);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_message_id_creation() {
        let id1 = MessageId::new();
        let id2 = MessageId::new();

        assert_ne!(id1, id2);
        assert!(!id1.as_str().is_empty());
    }

    #[test]
    fn test_message_priority_ordering() {
        assert!(MessagePriority::Critical > MessagePriority::High);
        assert!(MessagePriority::High > MessagePriority::Normal);
        assert!(MessagePriority::Normal > MessagePriority::Low);
    }

    #[test]
    fn test_delivery_options_default() {
        let options = DeliveryOptions::default();
        assert_eq!(options.priority, MessagePriority::Normal);
        assert_eq!(options.timeout, Duration::from_secs(30));
        assert!(!options.require_ack);
        assert_eq!(options.max_retries, 3);
    }

    #[test]
    fn test_agent_message_creation() {
        let from = AgentPid::new();
        let payload = "test message";

        // Test cast message
        let cast_msg = AgentMessage::cast(from.clone(), payload);
        assert_eq!(cast_msg.from(), Some(&from));
        assert!(!cast_msg.expects_response());

        // Test call message
        let (call_msg, _reply_rx) =
            AgentMessage::call(from.clone(), payload, Duration::from_secs(5));
        assert_eq!(call_msg.from(), Some(&from));
        assert!(call_msg.expects_response());

        // Test info message
        let info_msg = AgentMessage::info(SystemInfo::HealthCheck {
            agent_id: from.clone(),
            timestamp: Utc::now(),
        });
        assert_eq!(info_msg.from(), None);
        assert!(!info_msg.expects_response());
    }

    #[test]
    fn test_message_envelope() {
        let to = AgentPid::new();
        let from = AgentPid::new();
        let payload = serde_json::json!({"test": "data"});
        let options = DeliveryOptions::default();

        let mut envelope =
            MessageEnvelope::new(to.clone(), "test_message".to_string(), payload, options)
                .with_from(from.clone());

        assert_eq!(envelope.to, to);
        assert_eq!(envelope.from, Some(from));
        assert_eq!(envelope.attempts, 0);
        assert!(!envelope.max_retries_exceeded());
        assert!(!envelope.is_expired(Utc::now()));

        // Test attempt increment
        envelope.increment_attempts();
        assert_eq!(envelope.attempts, 1);
    }

    #[test]
    fn test_typed_message() {
        #[derive(Debug, PartialEq, Clone)]
        struct TestPayload {
            data: String,
        }

        let payload = TestPayload {
            data: "test".to_string(),
        };
        let from = AgentPid::new();

        let msg = TypedMessage::new(payload.clone()).with_from(from.clone());

        assert_eq!(msg.from, Some(from));
        assert_eq!(msg.payload.data, "test");
    }

    #[test]
    fn message_not_expired_before_timeout() {
        let options = DeliveryOptions {
            timeout: Duration::from_secs(30),
            ..Default::default()
        };
        let envelope = MessageEnvelope::new(
            AgentPid::new(),
            "test".to_string(),
            serde_json::Value::String("payload".to_string()),
            options,
        );
        // 29 seconds later: not expired
        let now = envelope.created_at + chrono::Duration::seconds(29);
        assert!(!envelope.is_expired(now));
    }

    #[test]
    fn message_not_expired_at_exact_boundary() {
        let options = DeliveryOptions {
            timeout: Duration::from_secs(30),
            ..Default::default()
        };
        let envelope = MessageEnvelope::new(
            AgentPid::new(),
            "test".to_string(),
            serde_json::Value::String("payload".to_string()),
            options,
        );
        // Exactly 30 seconds: not expired (> not >=)
        let now = envelope.created_at + chrono::Duration::seconds(30);
        assert!(!envelope.is_expired(now));
    }

    #[test]
    fn message_expired_one_ms_over_timeout() {
        let options = DeliveryOptions {
            timeout: Duration::from_secs(30),
            ..Default::default()
        };
        let envelope = MessageEnvelope::new(
            AgentPid::new(),
            "test".to_string(),
            serde_json::Value::String("payload".to_string()),
            options,
        );
        // 30 seconds + 1ms: expired
        let now = envelope.created_at + chrono::Duration::milliseconds(30_001);
        assert!(envelope.is_expired(now));
    }
}