beavers 0.0.2

Typed message processing for Kafka, Pulsar, RabbitMQ, SQS, Azure Service Bus, and HTTP with explicit delivery semantics
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
use crate::error::BoxError;
use crate::{codec::Decoder, message::OrderingKey};
use serde::Serialize;
use std::fmt::Debug;

#[cfg(feature = "kafka")]
use crate::adapters::kafka::{KafkaMetadata, KafkaRecord, text_headers};
#[cfg(feature = "pubsub")]
use crate::adapters::pubsub::{PubSubAttributes, PubSubMetadata, PubSubRecord};
#[cfg(feature = "pulsar")]
use crate::adapters::pulsar::{PulsarMessageId, PulsarMetadata, PulsarRecord};
#[cfg(feature = "rabbitmq")]
use crate::adapters::rabbitmq::{
    RabbitMqHeaders, RabbitMqMetadata, RabbitMqProperties, RabbitMqRecord,
    text_headers as rabbitmq_text_headers,
};
#[cfg(feature = "servicebus")]
use crate::adapters::servicebus::{
    ServiceBusApplicationProperties, ServiceBusMetadata, ServiceBusProperties, ServiceBusRecord,
    text_properties as servicebus_text_properties,
};
#[cfg(feature = "sqs")]
use crate::adapters::sqs::{SqsAttributes, SqsMetadata, SqsRecord, text_attributes};
#[cfg(feature = "pulsar")]
use std::collections::HashMap;

/// A received record with its payload left undecoded, as a
/// [`TestSource`](super::TestSource) delivers it.
///
/// The record is also the delivery's [`SourceMessage::Raw`] form, so dead
/// letters carry it exactly as the adapter's own raw record would.
///
/// [`SourceMessage::Raw`]: crate::message::SourceMessage::Raw
pub trait TestRecord: Clone + Debug + Serialize + Send + Sync + 'static {
    /// The handler input decoded from this record, such as `KafkaRecord<T>`
    /// for a `KafkaRecord<Vec<u8>>`.
    type Decoded<T: Clone + Send + Sync + 'static>: Clone + Send + Sync + 'static;

    /// Decode the payload with the source's codec, keeping the metadata.
    fn decode<C>(&self, codec: &C) -> Result<Self::Decoded<C::Value>, BoxError>
    where
        C: Decoder<Value: Clone + Send + Sync + 'static>;

    /// The ordering scope the owning adapter assigns to this record.
    fn ordering_key(&self) -> Option<OrderingKey> {
        None
    }

    /// The trace-context fields the owning adapter reads from this record.
    fn propagation_fields(&self) -> Vec<(&str, &str)> {
        Vec::new()
    }
}

/// A bare payload without record metadata. Deliveries have no ordering scope.
impl TestRecord for Vec<u8> {
    type Decoded<T: Clone + Send + Sync + 'static> = T;

    fn decode<C>(&self, codec: &C) -> Result<C::Value, BoxError>
    where
        C: Decoder<Value: Clone + Send + Sync + 'static>,
    {
        codec.decode(self)
    }
}

/// Decodes like a [`KafkaSource`](crate::adapters::kafka::KafkaSource): a null
/// value stays `None`. The ordering scope is the topic partition, and UTF-8
/// headers carry trace context.
#[cfg(feature = "kafka")]
impl TestRecord for KafkaRecord<Vec<u8>> {
    type Decoded<T: Clone + Send + Sync + 'static> = KafkaRecord<T>;

    fn decode<C>(&self, codec: &C) -> Result<KafkaRecord<C::Value>, BoxError>
    where
        C: Decoder<Value: Clone + Send + Sync + 'static>,
    {
        Ok(KafkaRecord {
            key: self.key.clone(),
            value: self
                .value
                .as_deref()
                .map(|bytes| codec.decode(bytes))
                .transpose()?,
            headers: self.headers.clone(),
            metadata: self.metadata.clone(),
        })
    }

    fn ordering_key(&self) -> Option<OrderingKey> {
        Some(OrderingKey::new(
            self.metadata.topic.as_str(),
            i64::from(self.metadata.partition),
        ))
    }

    fn propagation_fields(&self) -> Vec<(&str, &str)> {
        text_headers(
            self.headers
                .iter()
                .map(|(name, value)| (name.as_str(), value.as_deref())),
        )
    }
}

/// Decodes like a [`PulsarSource`](crate::adapters::pulsar::PulsarSource): a
/// null value stays `None`. The ordering scope is the topic partition, as for
/// Exclusive and Failover subscriptions, and properties carry trace context.
#[cfg(feature = "pulsar")]
impl TestRecord for PulsarRecord<Vec<u8>> {
    type Decoded<T: Clone + Send + Sync + 'static> = PulsarRecord<T>;

    fn decode<C>(&self, codec: &C) -> Result<PulsarRecord<C::Value>, BoxError>
    where
        C: Decoder<Value: Clone + Send + Sync + 'static>,
    {
        Ok(PulsarRecord {
            value: self
                .value
                .as_deref()
                .map(|bytes| codec.decode(bytes))
                .transpose()?,
            key: self.key.clone(),
            properties: self.properties.clone(),
            event_time: self.event_time,
            metadata: self.metadata.clone(),
        })
    }

    fn ordering_key(&self) -> Option<OrderingKey> {
        Some(OrderingKey::new(
            self.metadata.topic.as_str(),
            i64::from(self.metadata.message_id.partition),
        ))
    }

    fn propagation_fields(&self) -> Vec<(&str, &str)> {
        self.properties
            .iter()
            .map(|(name, value)| (name.as_str(), value.as_str()))
            .collect()
    }
}

/// Decodes like a [`RabbitMqSource`](crate::adapters::rabbitmq::RabbitMqSource).
/// Deliveries have no ordering scope, as for a source that is not
/// [`ordered`](crate::adapters::rabbitmq::RabbitMqSource::ordered), and
/// string headers carry trace context.
#[cfg(feature = "rabbitmq")]
impl TestRecord for RabbitMqRecord<Vec<u8>> {
    type Decoded<T: Clone + Send + Sync + 'static> = RabbitMqRecord<T>;

    fn decode<C>(&self, codec: &C) -> Result<RabbitMqRecord<C::Value>, BoxError>
    where
        C: Decoder<Value: Clone + Send + Sync + 'static>,
    {
        Ok(RabbitMqRecord {
            value: codec.decode(&self.value)?,
            headers: self.headers.clone(),
            properties: self.properties.clone(),
            metadata: self.metadata.clone(),
        })
    }

    fn propagation_fields(&self) -> Vec<(&str, &str)> {
        rabbitmq_text_headers(&self.headers)
    }
}

/// Decodes like a [`PubSubSource`](crate::adapters::pubsub::PubSubSource). A
/// message with an ordering key is ordered by it, and attributes carry trace
/// context.
#[cfg(feature = "pubsub")]
impl TestRecord for PubSubRecord<Vec<u8>> {
    type Decoded<T: Clone + Send + Sync + 'static> = PubSubRecord<T>;

    fn decode<C>(&self, codec: &C) -> Result<PubSubRecord<C::Value>, BoxError>
    where
        C: Decoder<Value: Clone + Send + Sync + 'static>,
    {
        Ok(PubSubRecord {
            value: codec.decode(&self.value)?,
            attributes: self.attributes.clone(),
            ordering_key: self.ordering_key.clone(),
            metadata: self.metadata.clone(),
        })
    }

    fn ordering_key(&self) -> Option<OrderingKey> {
        let key = self.ordering_key.as_deref()?;
        Some(OrderingKey::new(self.metadata.subscription.as_str(), 0).with_key(key.as_bytes()))
    }

    fn propagation_fields(&self) -> Vec<(&str, &str)> {
        self.attributes
            .iter()
            .map(|(name, value)| (name.as_str(), value.as_str()))
            .collect()
    }
}

/// Decodes like an [`SqsSource`](crate::adapters::sqs::SqsSource). A FIFO
/// queue message, whose queue URL ends in `.fifo`, is ordered by its message
/// group, and `String` attributes carry trace context.
#[cfg(feature = "sqs")]
impl TestRecord for SqsRecord<Vec<u8>> {
    type Decoded<T: Clone + Send + Sync + 'static> = SqsRecord<T>;

    fn decode<C>(&self, codec: &C) -> Result<SqsRecord<C::Value>, BoxError>
    where
        C: Decoder<Value: Clone + Send + Sync + 'static>,
    {
        Ok(SqsRecord {
            value: codec.decode(&self.value)?,
            attributes: self.attributes.clone(),
            metadata: self.metadata.clone(),
        })
    }

    fn ordering_key(&self) -> Option<OrderingKey> {
        let group = self.metadata.message_group_id.as_deref()?;
        self.metadata.queue_url.ends_with(".fifo").then(|| {
            OrderingKey::new(self.metadata.queue_url.as_str(), 0).with_key(group.as_bytes())
        })
    }

    fn propagation_fields(&self) -> Vec<(&str, &str)> {
        text_attributes(&self.attributes)
    }
}

/// Decodes like a
/// [`ServiceBusSource`](crate::adapters::servicebus::ServiceBusSource): records
/// are not ordered, and `String` application properties carry trace context.
#[cfg(feature = "servicebus")]
impl TestRecord for ServiceBusRecord<Vec<u8>> {
    type Decoded<T: Clone + Send + Sync + 'static> = ServiceBusRecord<T>;

    fn decode<C>(&self, codec: &C) -> Result<ServiceBusRecord<C::Value>, BoxError>
    where
        C: Decoder<Value: Clone + Send + Sync + 'static>,
    {
        Ok(ServiceBusRecord {
            value: codec.decode(&self.value)?,
            application_properties: self.application_properties.clone(),
            properties: self.properties.clone(),
            metadata: self.metadata.clone(),
        })
    }

    fn propagation_fields(&self) -> Vec<(&str, &str)> {
        servicebus_text_properties(&self.application_properties)
    }
}

/// A Kafka record at `offset` of a topic partition, without key, headers, or
/// timestamp. Set the public fields for anything else, such as `value = None`
/// for a tombstone.
#[cfg(feature = "kafka")]
pub fn kafka_record(
    topic: impl Into<String>,
    partition: i32,
    offset: i64,
    value: impl Into<Vec<u8>>,
) -> KafkaRecord<Vec<u8>> {
    KafkaRecord {
        key: None,
        value: Some(value.into()),
        headers: Vec::new(),
        metadata: KafkaMetadata {
            topic: topic.into(),
            partition,
            offset,
            timestamp: None,
        },
    }
}

/// A Pulsar message at `entry_id` of ledger 0 on a non-partitioned topic,
/// without key, properties, or event time, published at time 0. Set the public
/// fields for anything else, such as `metadata.message_id.partition` for a
/// partition topic or `value = None` for a tombstone.
#[cfg(feature = "pulsar")]
pub fn pulsar_record(
    topic: impl Into<String>,
    entry_id: u64,
    value: impl Into<Vec<u8>>,
) -> PulsarRecord<Vec<u8>> {
    PulsarRecord {
        value: Some(value.into()),
        key: None,
        properties: HashMap::new(),
        event_time: None,
        metadata: PulsarMetadata {
            topic: topic.into(),
            message_id: PulsarMessageId {
                ledger_id: 0,
                entry_id,
                partition: -1,
                batch_index: -1,
            },
            publish_time: 0,
        },
    }
}

/// A RabbitMQ message with `delivery_tag`, consumed from `queue` after being
/// published to the default exchange with the queue name as its routing key,
/// persistent and not redelivered, without headers or properties. Set the
/// public fields for anything else.
#[cfg(feature = "rabbitmq")]
pub fn rabbitmq_record(
    queue: impl Into<String>,
    delivery_tag: u64,
    value: impl Into<Vec<u8>>,
) -> RabbitMqRecord<Vec<u8>> {
    let queue = queue.into();
    RabbitMqRecord {
        value: value.into(),
        headers: RabbitMqHeaders::new(),
        properties: RabbitMqProperties::default(),
        metadata: RabbitMqMetadata {
            routing_key: queue.clone(),
            queue,
            exchange: String::new(),
            redelivered: false,
            persistent: true,
            delivery_tag,
        },
    }
}

/// A Pub/Sub message with `message_id` received from `subscription`, without
/// attributes, ordering key, publish time, or delivery attempt. Set the public
/// fields for anything else, such as `ordering_key`.
#[cfg(feature = "pubsub")]
pub fn pubsub_record(
    subscription: impl Into<String>,
    message_id: impl Into<String>,
    value: impl Into<Vec<u8>>,
) -> PubSubRecord<Vec<u8>> {
    PubSubRecord {
        value: value.into(),
        attributes: PubSubAttributes::new(),
        ordering_key: None,
        metadata: PubSubMetadata {
            subscription: subscription.into(),
            message_id: message_id.into(),
            publish_time: None,
            delivery_attempt: None,
        },
    }
}

/// An SQS message with `message_id` received from `queue_url` for the first
/// time, without attributes, timestamps, or FIFO fields. Set the public fields
/// for anything else, such as `metadata.message_group_id` on a FIFO queue.
#[cfg(feature = "sqs")]
pub fn sqs_record(
    queue_url: impl Into<String>,
    message_id: impl Into<String>,
    value: impl Into<Vec<u8>>,
) -> SqsRecord<Vec<u8>> {
    SqsRecord {
        value: value.into(),
        attributes: SqsAttributes::new(),
        metadata: SqsMetadata {
            queue_url: queue_url.into(),
            message_id: message_id.into(),
            receive_count: 1,
            sent_timestamp: None,
            first_receive_timestamp: None,
            message_group_id: None,
            deduplication_id: None,
            sequence_number: None,
        },
    }
}

/// A Service Bus message with `sequence_number` received from `entity_path`
/// for the first time, without application properties, message properties, or
/// timestamps, and with a nil lock token. Set the public fields for anything
/// else.
#[cfg(feature = "servicebus")]
pub fn servicebus_record(
    entity_path: impl Into<String>,
    sequence_number: i64,
    value: impl Into<Vec<u8>>,
) -> ServiceBusRecord<Vec<u8>> {
    ServiceBusRecord {
        value: value.into(),
        application_properties: ServiceBusApplicationProperties::new(),
        properties: ServiceBusProperties::default(),
        metadata: ServiceBusMetadata {
            entity_path: entity_path.into(),
            sequence_number,
            enqueued_time: None,
            scheduled_enqueue_time: None,
            delivery_count: 1,
            lock_token: "00000000-0000-0000-0000-000000000000".to_owned(),
            dead_letter_source: None,
        },
    }
}