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
//! AMQP broker.

use amq_protocol_types::{AMQPValue, FieldArray};
use async_trait::async_trait;
use lapin::options::{
    BasicAckOptions, BasicConsumeOptions, BasicPublishOptions, BasicQosOptions, QueueDeclareOptions,
};
use lapin::types::FieldTable;
use lapin::{BasicProperties, Channel, Connection, ConnectionProperties, Queue};
use log::debug;
use std::collections::HashMap;

use super::Broker;
use crate::protocol::{Message, MessageHeaders, MessageProperties, TryIntoMessage};
use crate::{Error, ErrorKind};

struct Config {
    broker_url: String,
    prefetch_count: Option<u16>,
    queues: HashMap<String, QueueDeclareOptions>,
}

/// Builds an AMQP broker with a custom configuration.
pub struct AMQPBrokerBuilder {
    config: Config,
}

impl AMQPBrokerBuilder {
    /// Create a new `AMQPBrokerBuilder`.
    pub fn new(broker_url: &str) -> Self {
        Self {
            config: Config {
                broker_url: broker_url.into(),
                prefetch_count: Some(1),
                queues: HashMap::new(),
            },
        }
    }

    /// Set the worker [prefetch
    /// count](https://www.rabbitmq.com/confirms.html#channel-qos-prefetch).
    pub fn prefetch_count(mut self, prefetch_count: Option<u16>) -> Self {
        self.config.prefetch_count = prefetch_count;
        self
    }

    /// Add / register a queue.
    pub fn queue(mut self, name: &str) -> Self {
        self.config.queues.insert(
            name.into(),
            QueueDeclareOptions {
                passive: false,
                durable: true,
                exclusive: false,
                auto_delete: false,
                nowait: false,
            },
        );
        self
    }

    /// Build an `AMQPBroker`.
    pub async fn build(self) -> Result<AMQPBroker, Error> {
        let conn =
            Connection::connect(&self.config.broker_url, ConnectionProperties::default()).await?;
        let channel = conn.create_channel().await?;
        if let Some(prefetch_count) = self.config.prefetch_count {
            channel
                .basic_qos(prefetch_count, BasicQosOptions::default())
                .await?;
        }
        let mut queues: HashMap<String, Queue> = HashMap::new();
        for (queue_name, queue_options) in &self.config.queues {
            let queue = channel
                .queue_declare(queue_name, queue_options.clone(), FieldTable::default())
                .await?;
            queues.insert(queue_name.into(), queue);
        }
        Ok(AMQPBroker { channel, queues })
    }
}

/// An AMQP broker.
pub struct AMQPBroker {
    channel: Channel,
    queues: HashMap<String, Queue>,
}

impl AMQPBroker {
    /// Get an `AMQPBrokerBuilder` for creating an AMQP broker with a custom configuration.
    pub fn builder(broker_url: &str) -> AMQPBrokerBuilder {
        AMQPBrokerBuilder::new(broker_url)
    }
}

#[async_trait]
impl Broker for AMQPBroker {
    type Delivery = lapin::message::Delivery;
    type DeliveryError = lapin::Error;
    type Consumer = lapin::Consumer;
    type ConsumerIterator = lapin::ConsumerIterator;

    async fn consume(&self, queue: &str) -> Result<Self::Consumer, Error> {
        let queue = self
            .queues
            .get(queue)
            .ok_or_else::<Error, _>(|| ErrorKind::UnknownQueueError(queue.into()).into())?;
        self.channel
            .basic_consume(
                queue,
                "",
                BasicConsumeOptions::default(),
                FieldTable::default(),
            )
            .await
            .map_err(|e| e.into())
    }

    async fn ack(&self, delivery: Self::Delivery) -> Result<(), Error> {
        self.channel
            .basic_ack(delivery.delivery_tag, BasicAckOptions::default())
            .await
            .map_err(|e| e.into())
    }

    async fn send(&self, message: &Message, queue: &str) -> Result<(), Error> {
        let properties = message.delivery_properties();
        debug!("properties: {:?}", properties);
        self.channel
            .basic_publish(
                "",
                queue,
                BasicPublishOptions::default(),
                message.raw_data.clone(),
                properties,
            )
            .await?;

        Ok(())
    }
}

impl Message {
    fn delivery_properties(&self) -> BasicProperties {
        let mut properties = BasicProperties::default()
            .with_correlation_id(self.properties.correlation_id.clone().into())
            .with_content_type(self.properties.content_type.clone().into())
            .with_content_encoding(self.properties.content_encoding.clone().into())
            .with_headers(self.delivery_headers())
            .with_priority(0)
            .with_delivery_mode(2);
        if let Some(ref reply_to) = self.properties.reply_to {
            properties = properties.with_reply_to(reply_to.clone().into());
        }
        properties
    }

    fn delivery_headers(&self) -> FieldTable {
        let mut headers = FieldTable::default();
        headers.insert(
            "id".into(),
            AMQPValue::LongString(self.headers.id.clone().into()),
        );
        headers.insert(
            "task".into(),
            AMQPValue::LongString(self.headers.task.clone().into()),
        );
        if let Some(ref lang) = self.headers.lang {
            headers.insert("lang".into(), AMQPValue::LongString(lang.clone().into()));
        }
        if let Some(ref root_id) = self.headers.root_id {
            headers.insert(
                "root_id".into(),
                AMQPValue::LongString(root_id.clone().into()),
            );
        }
        if let Some(ref parent_id) = self.headers.parent_id {
            headers.insert(
                "parent_id".into(),
                AMQPValue::LongString(parent_id.clone().into()),
            );
        }
        if let Some(ref group) = self.headers.group {
            headers.insert("group".into(), AMQPValue::LongString(group.clone().into()));
        }
        if let Some(ref meth) = self.headers.meth {
            headers.insert("meth".into(), AMQPValue::LongString(meth.clone().into()));
        }
        if let Some(ref shadow) = self.headers.shadow {
            headers.insert(
                "shadow".into(),
                AMQPValue::LongString(shadow.clone().into()),
            );
        }
        if let Some(ref eta) = self.headers.eta {
            headers.insert("eta".into(), AMQPValue::LongString(eta.clone().into()));
        }
        if let Some(ref expires) = self.headers.expires {
            headers.insert(
                "expires".into(),
                AMQPValue::LongString(expires.clone().into()),
            );
        }
        if let Some(retries) = self.headers.retries {
            headers.insert("retries".into(), AMQPValue::LongUInt(retries));
        }
        let mut timelimit = FieldArray::default();
        if let Some(t) = self.headers.timelimit.0 {
            timelimit.push(AMQPValue::LongUInt(t));
        } else {
            timelimit.push(AMQPValue::Void);
        }
        if let Some(t) = self.headers.timelimit.1 {
            timelimit.push(AMQPValue::LongUInt(t));
        } else {
            timelimit.push(AMQPValue::Void);
        }
        headers.insert("timelimit".into(), AMQPValue::FieldArray(timelimit));
        if let Some(ref argsrepr) = self.headers.argsrepr {
            headers.insert(
                "argsrepr".into(),
                AMQPValue::LongString(argsrepr.clone().into()),
            );
        }
        if let Some(ref kwargsrepr) = self.headers.kwargsrepr {
            headers.insert(
                "kwargsrepr".into(),
                AMQPValue::LongString(kwargsrepr.clone().into()),
            );
        }
        if let Some(ref origin) = self.headers.origin {
            headers.insert(
                "origin".into(),
                AMQPValue::LongString(origin.clone().into()),
            );
        }
        headers
    }
}

impl TryIntoMessage for lapin::message::Delivery {
    fn try_into_message(&self) -> Result<Message, Error> {
        let headers = self
            .properties
            .headers()
            .as_ref()
            .ok_or_else::<Error, _>(|| {
                ErrorKind::AMQPMessageParseError("missing headers".into()).into()
            })?;
        Ok(Message {
            properties: MessageProperties {
                correlation_id: self
                    .properties
                    .correlation_id()
                    .as_ref()
                    .map(|v| v.to_string())
                    .ok_or_else::<Error, _>(|| {
                        ErrorKind::AMQPMessageParseError("missing correlation_id".into()).into()
                    })?,
                content_type: self
                    .properties
                    .content_type()
                    .as_ref()
                    .map(|v| v.to_string())
                    .ok_or_else::<Error, _>(|| {
                        ErrorKind::AMQPMessageParseError("missing content_type".into()).into()
                    })?,
                content_encoding: self
                    .properties
                    .content_encoding()
                    .as_ref()
                    .map(|v| v.to_string())
                    .ok_or_else::<Error, _>(|| {
                        ErrorKind::AMQPMessageParseError("missing content_encoding".into()).into()
                    })?,
                reply_to: self.properties.reply_to().as_ref().map(|v| v.to_string()),
            },
            headers: MessageHeaders {
                id: headers
                    .inner()
                    .get("id")
                    .and_then(|v| match v {
                        AMQPValue::ShortString(s) => Some(s.to_string()),
                        AMQPValue::LongString(s) => Some(s.to_string()),
                        _ => None,
                    })
                    .ok_or_else::<Error, _>(|| {
                        ErrorKind::AMQPMessageParseError("invalid or missing 'id'".into()).into()
                    })?,
                task: headers
                    .inner()
                    .get("task")
                    .and_then(|v| match v {
                        AMQPValue::ShortString(s) => Some(s.to_string()),
                        AMQPValue::LongString(s) => Some(s.to_string()),
                        _ => None,
                    })
                    .ok_or_else::<Error, _>(|| {
                        ErrorKind::AMQPMessageParseError("invalid or missing 'task'".into()).into()
                    })?,
                lang: headers.inner().get("lang").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                root_id: headers.inner().get("root_id").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                parent_id: headers.inner().get("parent_id").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                group: headers.inner().get("group").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                meth: headers.inner().get("meth").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                shadow: headers.inner().get("shadow").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                eta: headers.inner().get("eta").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                expires: headers.inner().get("expires").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                retries: headers.inner().get("retries").and_then(|v| match v {
                    AMQPValue::ShortShortInt(n) => Some(*n as u32),
                    AMQPValue::ShortShortUInt(n) => Some(*n as u32),
                    AMQPValue::ShortInt(n) => Some(*n as u32),
                    AMQPValue::ShortUInt(n) => Some(*n as u32),
                    AMQPValue::LongInt(n) => Some(*n as u32),
                    AMQPValue::LongUInt(n) => Some(*n as u32),
                    AMQPValue::LongLongInt(n) => Some(*n as u32),
                    _ => None,
                }),
                timelimit: headers
                    .inner()
                    .get("timelimit")
                    .and_then(|v| match v {
                        AMQPValue::FieldArray(a) => {
                            let a = a.as_slice().to_vec();
                            if a.len() == 2 {
                                let soft = match a[0] {
                                    AMQPValue::ShortShortInt(n) => Some(n as u32),
                                    AMQPValue::ShortShortUInt(n) => Some(n as u32),
                                    AMQPValue::ShortInt(n) => Some(n as u32),
                                    AMQPValue::ShortUInt(n) => Some(n as u32),
                                    AMQPValue::LongInt(n) => Some(n as u32),
                                    AMQPValue::LongUInt(n) => Some(n as u32),
                                    AMQPValue::LongLongInt(n) => Some(n as u32),
                                    _ => None,
                                };
                                let hard = match a[1] {
                                    AMQPValue::ShortShortInt(n) => Some(n as u32),
                                    AMQPValue::ShortShortUInt(n) => Some(n as u32),
                                    AMQPValue::ShortInt(n) => Some(n as u32),
                                    AMQPValue::ShortUInt(n) => Some(n as u32),
                                    AMQPValue::LongInt(n) => Some(n as u32),
                                    AMQPValue::LongUInt(n) => Some(n as u32),
                                    AMQPValue::LongLongInt(n) => Some(n as u32),
                                    _ => None,
                                };
                                Some((soft, hard))
                            } else {
                                None
                            }
                        }
                        _ => None,
                    })
                    .unwrap_or((None, None)),
                argsrepr: headers.inner().get("argsrepr").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                kwargsrepr: headers.inner().get("kwargsrepr").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
                origin: headers.inner().get("origin").and_then(|v| match v {
                    AMQPValue::ShortString(s) => Some(s.to_string()),
                    AMQPValue::LongString(s) => Some(s.to_string()),
                    _ => None,
                }),
            },
            raw_data: self.data.clone(),
        })
    }
}