ollie 0.2.9

An abstraction layer on top of lapin, to align with traditional HTTP API routing.
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
//! This module provides a RabbitMQ router for consuming and handling messages
//! with asynchronous handlers.

use async_trait::async_trait;
use futures::StreamExt;
use lapin::BasicProperties;
use lapin::{options::*, types::FieldTable, Connection, ConnectionProperties, Consumer};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;

use crate::exchange::Exchange;
use crate::rabbit_result::RabbitResult;

#[async_trait]
/// Trait for handling asynchronous message processing.
/// - `S` represents the shared state that can be used by the handler.
pub trait AsyncHandler<S>: Send + Sync {
    /// Asynchronously handle incoming data.
    /// - `data`: The message data as a byte vector.
    /// - `state`: Shared state for processing messages.
    /// - Returns an optional `RabbitResult`.
    async fn handle(&self, data: Vec<u8>, state: Arc<Mutex<S>>) -> Option<RabbitResult>;
}

#[async_trait]
/// Implementation of `AsyncHandler` for closures.
/// This allows closures to be used as message handlers.
impl<S, F, Fut> AsyncHandler<S> for F
where
    S: Send + Sync + 'static,
    F: Fn(Vec<u8>, Arc<Mutex<S>>) -> Fut + Send + Sync,
    Fut: std::future::Future<Output = Option<RabbitResult>> + Send + 'static,
{
    async fn handle(&self, data: Vec<u8>, state: Arc<Mutex<S>>) -> Option<RabbitResult> {
        (self)(data, state).await
    }
}

/// Type alias for the shared state used by the router.
/// This is a mutex-protected shared state that can be accessed by the handlers.
/// Defined here so that it can be easily referenced in end user code.
/// - `S` represents the shared state.
///
pub type RabbitRouterState<S> = Arc<Mutex<S>>;

/// A router for managing RabbitMQ connections, channels, and routes.
pub struct RabbitRouter<S> {
    /// Shared RabbitMQ connection.
    pub connection: Arc<Connection>,
    /// Shared RabbitMQ channel.
    pub channel: Arc<lapin::Channel>,
    /// Map of queue names to their respective handlers.
    pub routes: Arc<Mutex<HashMap<String, Arc<dyn AsyncHandler<S>>>>>,
    /// Shared application state.
    pub state: Arc<Mutex<S>>,
}

impl<S> RabbitRouter<S>
where
    S: Send + Sync + 'static,
{
    /// Create a new `RabbitRouter` instance with a RabbitMQ connection.
    /// - `uri`: The RabbitMQ connection URI.
    /// - `initial_state`: The initial shared state.
    pub async fn new(uri: &str, initial_state: S) -> Self {
        let connection = Connection::connect(uri, ConnectionProperties::default())
            .await
            .expect("Failed to connect to RabbitMQ");
        let channel = connection
            .create_channel()
            .await
            .expect("Failed to create channel");

        RabbitRouter {
            connection: Arc::new(connection),
            channel: Arc::new(channel),
            routes: Arc::new(Mutex::new(HashMap::new())),
            state: Arc::new(Mutex::new(initial_state)),
        }
    }

    /// Add a route to a temporary queue bound to a specific exchange.
    /// - `exchange`: The name of the exchange.
    /// - `routing_key`: The routing key for the queue binding.
    /// - `result_exchange`: Optional exchange to send processing results.
    /// - `handler`: The message handler.
    pub async fn add_route_exchange<H>(
        &self,
        exchange: &str,
        routing_key: &str,
        result_exchange: Option<Exchange>,
        handler: H,
    ) -> Result<(), Box<dyn std::error::Error>>
    where
        H: AsyncHandler<S> + 'static,
    {
        let exchange = exchange.to_string();

        let routing_key = routing_key.to_string();
        let handler = Arc::new(handler);

        let channel = self.channel.clone();
        let mut exchange_options = ExchangeDeclareOptions::default();
        exchange_options.durable = false;
        // Declare the exchange
        channel
            .exchange_declare(
                &exchange,
                lapin::ExchangeKind::Topic,
                exchange_options,
                FieldTable::default(),
            )
            .await?;
        let mut options = QueueDeclareOptions::default();
        options.exclusive = true;
        options.durable = true;

        // Declare a temporary queue.
        let result = channel
            .queue_declare("", options, FieldTable::default())
            .await?;
        let queue_name = result.name().as_str().to_string();

        // Register the handler for the queue.
        let mut routes = self.routes.lock().await;
        routes.insert(queue_name.clone(), handler);
        let routes = self.routes.clone();

        let state = self.state.clone();

        // Bind the queue to the exchange.
        channel
            .queue_bind(
                &queue_name,
                &exchange,
                &routing_key,
                QueueBindOptions::default(),
                FieldTable::default(),
            )
            .await?;

        //Create the results exchange if one is provided
        Self::declare_result_exchange(channel.clone(), result_exchange.clone()).await?;

        // Start consuming messages.
        tokio::spawn(async move {
            let consumer = channel
                .basic_consume(
                    &queue_name,
                    "",
                    BasicConsumeOptions::default(),
                    FieldTable::default(),
                )
                .await
                .expect("Failed to start consumer");

            Self::consume_messages(
                queue_name,
                consumer,
                channel,
                result_exchange,
                routes,
                state,
            )
            .await;
        });
        Ok(())
    }

    /// Add a route to a specific queue.
    /// - `queue_name`: The name of the queue.
    /// - `source_exchange`: Optional exchange to bind the queue to to receive messages.
    /// - `result_exchange`: Optional exchange to send processing results.
    /// - `handler`: The message handler.
    pub async fn add_route_queue<H>(
        &self,
        queue_name: &str,
        source_exchange: Option<Exchange>,
        result_exchange: Option<Exchange>,
        handler: H,
    ) -> Result<(), Box<dyn std::error::Error>>
    where
        H: AsyncHandler<S> + 'static,
    {
        let queue_name = queue_name.to_string();
        let handler = Arc::new(handler);

        // Register the handler for the queue.
        let mut routes = self.routes.lock().await;
        routes.insert(queue_name.clone(), handler);
        let routes = self.routes.clone();

        let state = self.state.clone();

        // Declare the queue.
        let channel = self.channel.clone();
        let _queue = channel
            .queue_declare(
                &queue_name,
                QueueDeclareOptions::default(),
                FieldTable::default(),
            )
            .await
            .expect("Failed to declare queue");

        // Bind the queue to the exchange if one is provided.
        if let Some(queue_exchange) = source_exchange {
            let mut exchange_options = ExchangeDeclareOptions::default();
            exchange_options.durable = false;
            channel
                .exchange_declare(
                    &queue_exchange.name,
                    lapin::ExchangeKind::Topic,
                    exchange_options,
                    FieldTable::default(),
                )
                .await
                .expect("Failed to declare exchange");
            channel
                .queue_bind(
                    &queue_name,
                    &queue_exchange.name,
                    &queue_exchange.routing_key,
                    QueueBindOptions::default(),
                    FieldTable::default(),
                )
                .await
                .expect("Failed to bind queue to exchange");
        }

        //Create the results exchange if one is provided
        Self::declare_result_exchange(channel.clone(), result_exchange.clone()).await?;

        // Start consuming messages.
        tokio::spawn(async move {
            let consumer = channel
                .basic_consume(
                    &queue_name,
                    "",
                    BasicConsumeOptions::default(),
                    FieldTable::default(),
                )
                .await
                .expect("Failed to start consumer");

            Self::consume_messages(
                queue_name,
                consumer,
                channel,
                result_exchange,
                routes,
                state,
            )
            .await;
        });
        Ok(())
    }

    /// Internal method to consume messages from a queue.
    /// - `queue_name`: The name of the queue.
    /// - `consumer`: The consumer for the queue.
    /// - `channel`: The RabbitMQ channel.
    /// - `result_exchange`: Optional exchange to send processing results.
    /// - `routes`: Map of routes and their handlers.
    /// - `state`: Shared application state.
    async fn consume_messages(
        queue_name: String,
        mut consumer: Consumer,
        channel: Arc<lapin::Channel>,
        result_exchange: Option<Exchange>,
        routes: Arc<Mutex<HashMap<String, Arc<dyn AsyncHandler<S>>>>>,
        state: Arc<Mutex<S>>,
    ) {
        while let Some(delivery) = consumer.next().await {
            match delivery {
                Ok(delivery) => {
                    let data = delivery.data.clone();

                    // Retrieve and invoke the appropriate handler.
                    let routes = routes.lock().await;
                    if let Some(handler) = routes.get(&queue_name) {
                        let result = handler.handle(data, state.clone()).await;
                        if let Some(result) = result {
                            // Publish the result if a result exchange is provided.
                            if let Some(result_exchange) = &result_exchange {
                                let full_key = result.logging_level.to_string()
                                    + "."
                                    + &result.billing_type.to_string()
                                    + "."
                                    + result_exchange.routing_key.as_str();
                                let payload = serde_json::to_vec(&result).unwrap();

                                channel
                                    .basic_publish(
                                        &result_exchange.name,
                                        &full_key,
                                        BasicPublishOptions::default(),
                                        &payload,
                                        BasicProperties::default(),
                                    )
                                    .await
                                    .expect("Failed to publish message");
                            }
                        }
                    }

                    // Acknowledge the message.
                    delivery
                        .ack(BasicAckOptions::default())
                        .await
                        .expect("Failed to ack message");
                }
                Err(error) => eprintln!("Error receiving message: {:?}", error),
            }
        }
    }

    /// Internal method to consume messages from a queue.
    /// - `queue_name`: The name of the queue.
    /// - `consumer`: The consumer for the queue.
    /// - `channel`: The RabbitMQ channel.
    /// - `result_exchange`: Optional exchange to send processing results.
    /// - `routes`: Map of routes and their handlers.
    /// - `state`: Shared application state.
    async fn declare_result_exchange(
        channel: Arc<lapin::Channel>,
        result_exchange: Option<Exchange>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(exchange) = result_exchange {
            let mut exchange_options = ExchangeDeclareOptions::default();
            exchange_options.durable = false;
            channel
                .exchange_declare(
                    &exchange.name,
                    lapin::ExchangeKind::Topic,
                    exchange_options,
                    FieldTable::default(),
                )
                .await?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use lapin::BasicProperties;
    use tokio::time::{sleep, Duration};

    async fn test_handler(
        data: Vec<u8>,
        state: Arc<Mutex<Arc<Mutex<HashMap<String, i32>>>>>,
    ) -> Option<RabbitResult> {
        let state = state.lock().await;
        let mut inner_state = state.lock().await;
        let count = inner_state.entry("shared_counter".to_string()).or_insert(0);
        *count += 1;

        println!(
            "Handler for queue_1 received: {:?}, updated shared_counter: {}",
            String::from_utf8_lossy(&data),
            *count
        );
        None
    }

    #[tokio::test]
    async fn test_rabbit_router() {
        // Create a router
        let state = HashMap::new();
        let initial_state = Arc::new(Mutex::new(state));
        let router = RabbitRouter::new("amqp://127.0.0.1:5672", initial_state.clone()).await;

        // Add a route and send a test message
        router
            .add_route_queue("test_queue",None, None, test_handler)
            .await
            .expect("Failed to add route for queue_1");

        // Simulate sending a message to the queue
        let channel = router.channel.clone();
        let payload = b"Test message".to_vec();
        channel
            .basic_publish(
                "",
                "test_queue",
                BasicPublishOptions::default(),
                &payload,
                BasicProperties::default(),
            )
            .await
            .expect("Failed to publish message");

        // Give some time for the message to be processed
        sleep(Duration::from_secs(2)).await;
        println!("State: {:?}", initial_state.lock().await);
        assert!(initial_state.lock().await.get("shared_counter").is_some());
        assert!(initial_state.lock().await.get("shared_counter").unwrap() == &1);
    }

    #[tokio::test]
    async fn test_multiple_routes() {
        // Create a router
        let state = HashMap::new();
        let initial_state = Arc::new(Mutex::new(state));
        let router = RabbitRouter::new("amqp://127.0.0.1:5672/%2f", initial_state.clone()).await;

        // Add multiple routes
        let _ = router.add_route_queue("queue_1",None, None, test_handler).await;

        let _ = router.add_route_queue("queue_2",None, None, test_handler).await;

        // Simulate sending messages to the queues
        let channel = router.channel.clone();
        let payload_1 = b"Message for queue_1".to_vec();
        let payload_2 = b"Message for queue_2".to_vec();

        channel
            .basic_publish(
                "",
                "queue_1",
                BasicPublishOptions::default(),
                &payload_1,
                BasicProperties::default(),
            )
            .await
            .expect("Failed to publish message to queue_1");

        channel
            .basic_publish(
                "",
                "queue_2",
                BasicPublishOptions::default(),
                &payload_2,
                BasicProperties::default(),
            )
            .await
            .expect("Failed to publish message to queue_2");

        // Give some time for the messages to be processed
        sleep(Duration::from_secs(2)).await;
        assert!(initial_state.lock().await.get("shared_counter").is_some());
        assert!(initial_state.lock().await.get("shared_counter").unwrap() == &2);
    }

    #[tokio::test]
    async fn test_exchange_route() {
        // Create a router
        let state = HashMap::new();
        let initial_state = Arc::new(Mutex::new(state));
        let router = RabbitRouter::new("amqp://127.0.0.1:5672", initial_state.clone()).await;
        // Declare the exchange
        let channel = router.channel.clone();
        channel
            .exchange_declare(
                "test_exchange",
                lapin::ExchangeKind::Topic,
                ExchangeDeclareOptions::default(),
                FieldTable::default(),
            )
            .await
            .expect("Failed to declare exchange");
        // Add a route to an exchange
        let _ = router
            .add_route_exchange("test_exchange", "test.routing.key", None, test_handler)
            .await;

        // Simulate sending a message to the exchange
        let channel = router.channel.clone();
        let payload = b"Test exchange message".to_vec();
        channel
            .basic_publish(
                "test_exchange",
                "test.routing.key",
                BasicPublishOptions::default(),
                &payload,
                BasicProperties::default(),
            )
            .await
            .expect("Failed to publish message to exchange");
        println!("Message published to exchange");
        // Give some time for the message to be processed
        sleep(Duration::from_secs(2)).await;
        assert!(initial_state.lock().await.get("shared_counter").is_some());
        assert!(initial_state.lock().await.get("shared_counter").unwrap() == &1);
    }
}