armature-messaging 0.1.0

Message broker integrations for the Armature framework - RabbitMQ, Kafka, NATS, and AWS SQS/SNS
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
//! RabbitMQ message broker implementation

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use async_trait::async_trait;
use futures_util::StreamExt;
use lapin::{
    BasicProperties, Channel, Connection, ConnectionProperties, Consumer, options::*,
    types::FieldTable,
};
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};

use crate::{
    AckMode, Message, MessageBroker, MessageHandler, MessagingConfig, MessagingError,
    ProcessingResult, PublishOptions, SubscribeOptions, Subscription,
};

/// RabbitMQ message broker
pub struct RabbitMqBroker {
    connection: Arc<Connection>,
    channels: Arc<RwLock<Vec<Channel>>>,
    publish_channel: Channel,
    connected: Arc<AtomicBool>,
}

impl RabbitMqBroker {
    /// Connect to RabbitMQ
    pub async fn connect(config: &MessagingConfig) -> Result<Self, MessagingError> {
        info!(url = %config.url, "Connecting to RabbitMQ");

        let connection = Connection::connect(&config.url, ConnectionProperties::default()).await?;

        let publish_channel = connection.create_channel().await?;

        // Enable publisher confirms if requested
        publish_channel
            .confirm_select(ConfirmSelectOptions::default())
            .await?;

        info!("Connected to RabbitMQ successfully");

        Ok(Self {
            connection: Arc::new(connection),
            channels: Arc::new(RwLock::new(Vec::new())),
            publish_channel,
            connected: Arc::new(AtomicBool::new(true)),
        })
    }

    /// Declare a queue
    pub async fn declare_queue(
        &self,
        name: &str,
        options: QueueDeclareOptions,
    ) -> Result<(), MessagingError> {
        self.publish_channel
            .queue_declare(name, options, FieldTable::default())
            .await?;
        debug!(queue = name, "Queue declared");
        Ok(())
    }

    /// Declare an exchange
    pub async fn declare_exchange(
        &self,
        name: &str,
        kind: lapin::ExchangeKind,
        options: ExchangeDeclareOptions,
    ) -> Result<(), MessagingError> {
        self.publish_channel
            .exchange_declare(name, kind, options, FieldTable::default())
            .await?;
        debug!(exchange = name, "Exchange declared");
        Ok(())
    }

    /// Bind a queue to an exchange
    pub async fn bind_queue(
        &self,
        queue: &str,
        exchange: &str,
        routing_key: &str,
    ) -> Result<(), MessagingError> {
        self.publish_channel
            .queue_bind(
                queue,
                exchange,
                routing_key,
                QueueBindOptions::default(),
                FieldTable::default(),
            )
            .await?;
        debug!(
            queue = queue,
            exchange = exchange,
            routing_key = routing_key,
            "Queue bound to exchange"
        );
        Ok(())
    }

    fn build_properties(message: &Message) -> BasicProperties {
        let mut props = BasicProperties::default()
            .with_message_id(message.id.clone().into())
            .with_timestamp(message.timestamp.timestamp() as u64);

        if let Some(ref content_type) = message.content_type {
            props = props.with_content_type(content_type.clone().into());
        }

        if let Some(ref correlation_id) = message.correlation_id {
            props = props.with_correlation_id(correlation_id.clone().into());
        }

        if let Some(ref reply_to) = message.reply_to {
            props = props.with_reply_to(reply_to.clone().into());
        }

        if let Some(priority) = message.priority {
            props = props.with_priority(priority);
        }

        if let Some(ttl) = message.ttl {
            props = props.with_expiration(ttl.to_string().into());
        }

        // Add headers
        if !message.headers.is_empty() {
            let mut headers = FieldTable::default();
            for (key, value) in &message.headers {
                headers.insert(
                    key.clone().into(),
                    lapin::types::AMQPValue::LongString(value.clone().into()),
                );
            }
            props = props.with_headers(headers);
        }

        props
    }
}

#[async_trait]
impl MessageBroker for RabbitMqBroker {
    type Subscription = RabbitMqSubscription;

    async fn publish(&self, message: Message) -> Result<(), MessagingError> {
        self.publish_with_options(message, PublishOptions::default())
            .await
    }

    async fn publish_with_options(
        &self,
        message: Message,
        options: PublishOptions,
    ) -> Result<(), MessagingError> {
        let exchange = options.exchange.as_deref().unwrap_or("");
        let routing_key = options.routing_key.as_deref().unwrap_or(&message.topic);

        let mut props = Self::build_properties(&message);

        if options.persistent {
            props = props.with_delivery_mode(2);
        }

        debug!(
            exchange = exchange,
            routing_key = routing_key,
            message_id = %message.id,
            "Publishing message"
        );

        let confirm = self
            .publish_channel
            .basic_publish(
                exchange,
                routing_key,
                BasicPublishOptions::default(),
                &message.payload,
                props,
            )
            .await?;

        if options.confirm {
            confirm.await.map_err(|e| {
                error!(error = %e, "Publisher confirm failed");
                MessagingError::Publish(format!("Publisher confirm failed: {}", e))
            })?;
        }

        Ok(())
    }

    async fn subscribe(
        &self,
        topic: &str,
        handler: Arc<dyn MessageHandler>,
    ) -> Result<Self::Subscription, MessagingError> {
        self.subscribe_with_options(topic, handler, SubscribeOptions::default())
            .await
    }

    async fn subscribe_with_options(
        &self,
        topic: &str,
        handler: Arc<dyn MessageHandler>,
        options: SubscribeOptions,
    ) -> Result<Self::Subscription, MessagingError> {
        let channel = self.connection.create_channel().await?;

        // Set prefetch count if specified
        if let Some(prefetch) = options.prefetch_count {
            channel
                .basic_qos(prefetch, BasicQosOptions::default())
                .await?;
        }

        // Declare the queue
        channel
            .queue_declare(
                topic,
                QueueDeclareOptions {
                    durable: true,
                    ..Default::default()
                },
                FieldTable::default(),
            )
            .await?;

        let consumer_tag = options
            .consumer_group
            .unwrap_or_else(|| format!("armature-{}", uuid::Uuid::new_v4()));

        let consumer = channel
            .basic_consume(
                topic,
                &consumer_tag,
                BasicConsumeOptions {
                    no_ack: options.ack_mode == AckMode::None,
                    ..Default::default()
                },
                FieldTable::default(),
            )
            .await?;

        let active = Arc::new(AtomicBool::new(true));
        let subscription = RabbitMqSubscription {
            topic: topic.to_string(),
            consumer_tag: consumer_tag.clone(),
            channel: channel.clone(),
            active: active.clone(),
        };

        // Store channel for cleanup
        self.channels.write().await.push(channel.clone());

        // Spawn consumer task
        let topic_owned = topic.to_string();
        let ack_mode = options.ack_mode;
        tokio::spawn(async move {
            consume_messages(consumer, handler, channel, &topic_owned, ack_mode, active).await;
        });

        info!(queue = topic, consumer_tag = %consumer_tag, "Subscribed to queue");
        Ok(subscription)
    }

    fn is_connected(&self) -> bool {
        self.connected.load(Ordering::SeqCst) && self.connection.status().connected()
    }

    async fn close(&self) -> Result<(), MessagingError> {
        info!("Closing RabbitMQ connection");
        self.connected.store(false, Ordering::SeqCst);

        // Close all channels
        let channels = self.channels.read().await;
        for channel in channels.iter() {
            if let Err(e) = channel.close(200, "Normal shutdown").await {
                warn!(error = %e, "Error closing channel");
            }
        }

        // Close connection
        self.connection
            .close(200, "Normal shutdown")
            .await
            .map_err(|e| MessagingError::Connection(e.to_string()))?;

        Ok(())
    }
}

async fn consume_messages(
    mut consumer: Consumer,
    handler: Arc<dyn MessageHandler>,
    channel: Channel,
    topic: &str,
    ack_mode: AckMode,
    active: Arc<AtomicBool>,
) {
    while active.load(Ordering::SeqCst) {
        match consumer.next().await {
            Some(Ok(delivery)) => {
                let message = delivery_to_message(&delivery, topic);
                let delivery_tag = delivery.delivery_tag;

                match handler.handle(message).await {
                    Ok(result) => {
                        if ack_mode == AckMode::Auto || ack_mode == AckMode::Manual {
                            match result {
                                ProcessingResult::Success => {
                                    if let Err(e) = channel
                                        .basic_ack(delivery_tag, BasicAckOptions::default())
                                        .await
                                    {
                                        error!(error = %e, "Failed to ack message");
                                    }
                                }
                                ProcessingResult::Retry => {
                                    if let Err(e) = channel
                                        .basic_nack(
                                            delivery_tag,
                                            BasicNackOptions {
                                                requeue: true,
                                                ..Default::default()
                                            },
                                        )
                                        .await
                                    {
                                        error!(error = %e, "Failed to nack message for retry");
                                    }
                                }
                                ProcessingResult::DeadLetter | ProcessingResult::Reject => {
                                    if let Err(e) = channel
                                        .basic_reject(
                                            delivery_tag,
                                            BasicRejectOptions { requeue: false },
                                        )
                                        .await
                                    {
                                        error!(error = %e, "Failed to reject message");
                                    }
                                }
                            }
                        }
                    }
                    Err(e) => {
                        error!(error = %e, "Message handler error");
                        if ack_mode != AckMode::None {
                            let _ = channel
                                .basic_nack(
                                    delivery_tag,
                                    BasicNackOptions {
                                        requeue: true,
                                        ..Default::default()
                                    },
                                )
                                .await;
                        }
                    }
                }
            }
            Some(Err(e)) => {
                error!(error = %e, "Consumer error");
                break;
            }
            None => {
                debug!("Consumer stream ended");
                break;
            }
        }
    }
}

fn delivery_to_message(delivery: &lapin::message::Delivery, topic: &str) -> Message {
    let props = &delivery.properties;
    let mut headers = HashMap::new();

    if let Some(amqp_headers) = props.headers() {
        for (key, value) in amqp_headers.inner() {
            if let lapin::types::AMQPValue::LongString(s) = value {
                headers.insert(key.to_string(), s.to_string());
            }
        }
    }

    Message {
        id: props
            .message_id()
            .as_ref()
            .map(|s| s.to_string())
            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
        payload: delivery.data.clone(),
        headers,
        topic: topic.to_string(),
        timestamp: props
            .timestamp()
            .map(|ts| {
                chrono::DateTime::from_timestamp(ts as i64, 0).unwrap_or_else(chrono::Utc::now)
            })
            .unwrap_or_else(chrono::Utc::now),
        correlation_id: props.correlation_id().as_ref().map(|s| s.to_string()),
        reply_to: props.reply_to().as_ref().map(|s| s.to_string()),
        content_type: props.content_type().as_ref().map(|s| s.to_string()),
        priority: *props.priority(),
        ttl: props
            .expiration()
            .as_ref()
            .and_then(|s| s.to_string().parse().ok()),
    }
}

/// RabbitMQ subscription handle
pub struct RabbitMqSubscription {
    topic: String,
    consumer_tag: String,
    channel: Channel,
    active: Arc<AtomicBool>,
}

#[async_trait]
impl Subscription for RabbitMqSubscription {
    async fn unsubscribe(&self) -> Result<(), MessagingError> {
        self.active.store(false, Ordering::SeqCst);
        self.channel
            .basic_cancel(&self.consumer_tag, BasicCancelOptions::default())
            .await?;
        info!(consumer_tag = %self.consumer_tag, "Unsubscribed from queue");
        Ok(())
    }

    fn is_active(&self) -> bool {
        self.active.load(Ordering::SeqCst)
    }

    fn topic(&self) -> &str {
        &self.topic
    }
}