mecha10-core 0.6.2

Mecha10 core runtime and foundational types
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
//! Dead Letter Queue (DLQ) for Failed Message Processing
//!
//! Provides a mechanism to capture and handle messages that fail processing repeatedly.
//! This prevents infinite retry loops and data loss while enabling debugging and recovery.
//!
//! # Use Cases
//!
//! - Messages that fail validation
//! - Messages that cause processing errors
//! - Messages that exceed retry limits
//! - Poison messages that would block a queue
//!
//! # Example
//!
//! ```rust
//! use mecha10::prelude::*;
//! use mecha10::dead_letter::{DeadLetterQueue, FailedMessage};
//!
//! # async fn example(ctx: &Context) -> Result<()> {
//! let dlq = DeadLetterQueue::new("vision_processing");
//!
//! let mut images = ctx.subscribe(sensor::CAMERA_RGB).await?;
//!
//! while let Some(image) = images.recv().await {
//!     match process_image(&image).await {
//!         Ok(result) => {
//!             ctx.publish(&result).await?;
//!         }
//!         Err(e) => {
//!             // Send to dead letter queue
//!             dlq.send(
//!                 &image,
//!                 "vision_processing",
//!                 &e.to_string(),
//!                 None
//!             ).await?;
//!         }
//!     }
//! }
//! # Ok(())
//! # }
//! ```

use crate::error::{Mecha10Error, Result};
use crate::messages::Message;
use crate::prelude::now_micros;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};

/// Failed message with metadata for debugging and recovery
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailedMessage<T> {
    /// The original message that failed
    pub message: T,

    /// When the message failed
    pub failed_at: u64,

    /// Source topic or queue
    pub source: String,

    /// Error message
    pub error: String,

    /// Number of times this message failed
    pub retry_count: u32,

    /// Additional context for debugging
    pub metadata: HashMap<String, String>,

    /// Stack trace if available
    pub stack_trace: Option<String>,
}

impl<T: Message + Serialize> Message for FailedMessage<T> where FailedMessage<T>: Send + Sync + 'static {}

/// Configuration for dead letter queue behavior
#[derive(Debug, Clone)]
pub struct DeadLetterConfig {
    /// Maximum number of messages to keep in memory
    pub max_size: usize,

    /// Whether to persist failed messages to disk/database
    pub persist: bool,

    /// Path for persistence (if enabled)
    pub persist_path: Option<String>,

    /// Whether to publish failed messages to a DLQ topic
    pub publish_to_topic: bool,

    /// DLQ topic prefix (e.g., "/dlq/{source}")
    pub topic_prefix: String,
}

impl Default for DeadLetterConfig {
    fn default() -> Self {
        Self {
            max_size: 1000,
            persist: false,
            persist_path: None,
            publish_to_topic: true,
            topic_prefix: "/dlq".to_string(),
        }
    }
}

/// Dead Letter Queue for capturing failed messages
///
/// Provides multiple backends for storing and retrieving failed messages:
/// - In-memory queue (with size limit)
/// - Topic-based publishing (for monitoring)
/// - Optional persistence to disk
///
/// # Thread Safety
///
/// The DLQ is thread-safe and can be cloned cheaply (uses Arc internally).
#[derive(Clone)]
pub struct DeadLetterQueue {
    name: String,
    config: DeadLetterConfig,
    messages: Arc<RwLock<Vec<serde_json::Value>>>,
    stats: Arc<RwLock<DLQStats>>,
}

#[derive(Debug, Clone, Default)]
struct DLQStats {
    total_failed: u64,
    total_recovered: u64,
    total_dropped: u64,
}

impl DeadLetterQueue {
    /// Create a new dead letter queue
    ///
    /// # Arguments
    ///
    /// * `name` - Name for this DLQ (e.g., "vision_processor")
    ///
    /// # Example
    ///
    /// ```rust
    /// use mecha10::dead_letter::DeadLetterQueue;
    ///
    /// let dlq = DeadLetterQueue::new("my_processor");
    /// ```
    pub fn new(name: &str) -> Self {
        Self::with_config(name, DeadLetterConfig::default())
    }

    /// Create a new dead letter queue with custom configuration
    pub fn with_config(name: &str, config: DeadLetterConfig) -> Self {
        info!(
            "Creating dead letter queue '{}' (max_size: {}, persist: {})",
            name, config.max_size, config.persist
        );

        Self {
            name: name.to_string(),
            config,
            messages: Arc::new(RwLock::new(Vec::new())),
            stats: Arc::new(RwLock::new(DLQStats::default())),
        }
    }

    /// Send a failed message to the dead letter queue
    ///
    /// # Arguments
    ///
    /// * `message` - The message that failed processing
    /// * `source` - Source topic/queue
    /// * `error` - Error message
    /// * `retry_count` - Number of retries attempted
    ///
    /// # Example
    ///
    /// ```rust
    /// # use mecha10::prelude::*;
    /// # use mecha10::dead_letter::DeadLetterQueue;
    /// # async fn example(dlq: &DeadLetterQueue, image: &Image) -> Result<()> {
    /// dlq.send(
    ///     image,
    ///     "sensor/camera/rgb",
    ///     "Invalid image format",
    ///     Some(3)
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send<T: Message + Serialize + Clone>(
        &self,
        message: &T,
        source: &str,
        error: &str,
        retry_count: Option<u32>,
    ) -> Result<()> {
        self.send_with_metadata(message, source, error, retry_count, HashMap::new())
            .await
    }

    /// Send a failed message with additional metadata
    ///
    /// # Arguments
    ///
    /// * `message` - The message that failed
    /// * `source` - Source topic/queue
    /// * `error` - Error message
    /// * `retry_count` - Number of retries
    /// * `metadata` - Additional debugging context
    pub async fn send_with_metadata<T: Message + Serialize + Clone>(
        &self,
        message: &T,
        source: &str,
        error: &str,
        retry_count: Option<u32>,
        metadata: HashMap<String, String>,
    ) -> Result<()> {
        let failed_msg = FailedMessage {
            message: message.clone(),
            failed_at: now_micros(),
            source: source.to_string(),
            error: error.to_string(),
            retry_count: retry_count.unwrap_or(0),
            metadata,
            stack_trace: None, // Could be populated with backtrace
        };

        // Update stats
        {
            let mut stats = self.stats.write().await;
            stats.total_failed += 1;
        }

        // Serialize to JSON for storage
        let json = serde_json::to_value(&failed_msg)
            .map_err(|e| Mecha10Error::SerializationFailed(format!("Failed to serialize DLQ message: {}", e)))?;

        // Store in memory
        {
            let mut messages = self.messages.write().await;

            // Enforce size limit
            if messages.len() >= self.config.max_size {
                warn!(
                    "DLQ '{}' at capacity ({}), dropping oldest message",
                    self.name, self.config.max_size
                );
                messages.remove(0);

                let mut stats = self.stats.write().await;
                stats.total_dropped += 1;
            }

            messages.push(json.clone());
        }

        error!(
            "Message sent to DLQ '{}' from '{}': {} (retry_count: {})",
            self.name,
            source,
            error,
            retry_count.unwrap_or(0)
        );

        // Persist if configured
        if self.config.persist {
            self.persist_message(&json).await?;
        }

        // Publish to DLQ topic if configured
        if self.config.publish_to_topic {
            self.publish_to_dlq_topic(failed_msg.clone(), source).await?;
        }

        Ok(())
    }

    /// Get all failed messages
    ///
    /// # Returns
    ///
    /// Vector of failed messages as JSON values
    pub async fn get_all(&self) -> Vec<serde_json::Value> {
        let messages = self.messages.read().await;
        messages.clone()
    }

    /// Get failed messages from a specific source
    pub async fn get_by_source(&self, source: &str) -> Vec<serde_json::Value> {
        let messages = self.messages.read().await;
        messages
            .iter()
            .filter(|msg| {
                msg.get("source")
                    .and_then(|s| s.as_str())
                    .map(|s| s == source)
                    .unwrap_or(false)
            })
            .cloned()
            .collect()
    }

    /// Get the number of failed messages
    pub async fn len(&self) -> usize {
        let messages = self.messages.read().await;
        messages.len()
    }

    /// Check if the DLQ is empty
    pub async fn is_empty(&self) -> bool {
        self.len().await == 0
    }

    /// Clear all failed messages
    ///
    /// Use with caution - messages will be lost unless persisted elsewhere.
    pub async fn clear(&self) {
        let mut messages = self.messages.write().await;
        let count = messages.len();
        messages.clear();
        info!("Cleared {} messages from DLQ '{}'", count, self.name);
    }

    /// Remove and return a failed message for retry
    ///
    /// # Arguments
    ///
    /// * `index` - Index of the message to remove
    ///
    /// # Returns
    ///
    /// The removed message, or None if index is out of bounds
    pub async fn remove(&self, index: usize) -> Option<serde_json::Value> {
        let mut messages = self.messages.write().await;

        if index < messages.len() {
            let msg = messages.remove(index);

            let mut stats = self.stats.write().await;
            stats.total_recovered += 1;

            debug!("Removed message {} from DLQ '{}'", index, self.name);
            Some(msg)
        } else {
            None
        }
    }

    /// Get statistics about the DLQ
    ///
    /// # Returns
    ///
    /// (total_failed, total_recovered, total_dropped, current_count)
    pub async fn stats(&self) -> (u64, u64, u64, usize) {
        let stats = self.stats.read().await;
        let current = self.len().await;
        (stats.total_failed, stats.total_recovered, stats.total_dropped, current)
    }

    /// Persist a message to disk (if configured)
    async fn persist_message(&self, message: &serde_json::Value) -> Result<()> {
        if let Some(path) = &self.config.persist_path {
            // Simple file append - in production, use proper database
            let json_str = serde_json::to_string(message)
                .map_err(|e| Mecha10Error::SerializationFailed(format!("Failed to serialize: {}", e)))?;

            tokio::fs::write(path, json_str).await?;

            debug!("Persisted DLQ message to {}", path);
        }

        Ok(())
    }

    /// Publish failed message to DLQ topic
    async fn publish_to_dlq_topic<T: Message + Serialize + Clone>(
        &self,
        _failed_msg: FailedMessage<T>,
        source: &str,
    ) -> Result<()> {
        // In a real implementation, would use Context to publish
        // For now, just log
        debug!(
            "Would publish to DLQ topic: {}/{}/{}",
            self.config.topic_prefix, self.name, source
        );
        Ok(())
    }
}

impl std::fmt::Debug for DeadLetterQueue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DeadLetterQueue")
            .field("name", &self.name)
            .field("config", &self.config)
            .finish()
    }
}

/// Extension trait for adding DLQ support to message processing
///
/// # Example
///
/// ```rust
/// use mecha10::prelude::*;
/// use mecha10::dead_letter::{DeadLetterQueue, DeadLetterExt};
///
/// # async fn example(ctx: &Context) -> Result<()> {
/// let dlq = DeadLetterQueue::new("processor");
///
/// ctx.subscribe(sensor::CAMERA_RGB)
///     .await?
///     .process_with_dlq(&dlq, "sensor/camera/rgb", |image| async move {
///         // Processing logic
///         detect_objects(&image).await
///     })
///     .await?;
/// # Ok(())
/// # }
/// ```
pub trait DeadLetterExt<T> {
    /// Process messages with automatic DLQ handling
    fn process_with_dlq<F, Fut, R>(
        self,
        dlq: &DeadLetterQueue,
        source: &str,
        processor: F,
    ) -> impl std::future::Future<Output = Result<()>>
    where
        F: Fn(T) -> Fut,
        Fut: std::future::Future<Output = Result<R>>;
}

// Note: This trait implementation would need the actual Receiver type
// For now, it's a placeholder showing the API design