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
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
use super::{
    client::{Pulsar, partition_topics},
    config::{PulsarSubscriptionType, SourceConfig},
    record::{PulsarMessageId, PulsarMetadata, PulsarRecord},
};
use crate::{
    codec::Decoder,
    error::{BoxError, Context, Error, ensure},
    message::{OrderingKey, SourceMessage},
    retry::RetryPolicy,
    source::{Receive, ReceiveError, Source},
};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use futures_util::future::select_all;
use magnetar::{
    proto::{IncomingMessage, MessageId},
    runtime_tokio::Consumer,
};
use std::{
    collections::HashMap,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

/// Subscribes on the first `receive` call, which also validates the settings.
///
/// Built with [`Pulsar::source`]. A partitioned topic is consumed through one
/// consumer per partition. Closing the source closes its consumers; the client
/// stays open for the other sources and sinks of the handle.
pub struct PulsarSource<C> {
    pulsar: Pulsar,
    config: SourceConfig,
    codec: Arc<C>,
    connection: Option<Connection>,
    closed: bool,
}

struct Connection {
    consumers: Vec<Consumer>,
    closed: Arc<AtomicBool>,
    ack_retry: Arc<RetryPolicy>,
    /// The consumer polled first by the next `receive`, so that a busy
    /// partition cannot starve the others.
    next: usize,
}

impl<C> PulsarSource<C> {
    pub(super) fn new(pulsar: Pulsar, config: SourceConfig, codec: C) -> Self {
        Self {
            pulsar,
            config,
            codec: Arc::new(codec),
            connection: None,
            closed: false,
        }
    }

    /// How the broker distributes the subscription's messages among its
    /// consumers. Defaults to [`Shared`](PulsarSubscriptionType::Shared).
    pub fn subscription_type(mut self, subscription_type: PulsarSubscriptionType) -> Self {
        self.config.subscription_type = subscription_type;
        self
    }

    /// Messages each partition's consumer prefetches from the broker. Defaults
    /// to 100.
    pub fn buffer_size(mut self, buffer_size: usize) -> Self {
        self.config.buffer_size = buffer_size;
        self
    }

    /// Whether an empty payload is a null value, matching topic compaction,
    /// which deletes a key on an empty payload. Enabled by default.
    pub fn empty_payload_is_tombstone(mut self, enabled: bool) -> Self {
        self.config.empty_payload_is_tombstone = enabled;
        self
    }

    /// Attempts to acknowledge a delivery. An acknowledgement sent while the
    /// client reconnects after a topic unload or broker restart fails or times
    /// out, and a later attempt on the new session succeeds. Defaults to 5
    /// attempts with delays from 100 ms up to 2 s.
    pub fn ack_retry(mut self, ack_retry: RetryPolicy) -> Self {
        self.config.ack_retry = ack_retry;
        self
    }

    /// Checks the handle and source settings without network access.
    ///
    /// Fails when the handle is invalid, when the topic or subscription is
    /// empty, when `buffer_size` is zero, or when `ack_retry` is invalid.
    pub fn validate(&self) -> Result<(), Error> {
        self.pulsar.validate()?;
        self.config.validate()
    }

    async fn connect(&self) -> Result<Connection, BoxError> {
        self.config.validate()?;
        let client = self.pulsar.client().await?;
        let mut consumers = Vec::new();
        for topic in partition_topics(client, &self.config.topic).await? {
            let consumer = client
                .consumer(topic)
                .subscription(&self.config.subscription)
                .subscription_type(self.config.subscription_type.into())
                .receiver_queue_size(self.config.buffer_size)
                .subscribe()
                .await?;
            consumers.push(consumer);
        }
        Ok(Connection {
            consumers,
            closed: Arc::new(AtomicBool::new(false)),
            ack_retry: Arc::new(self.config.ack_retry.clone()),
            next: 0,
        })
    }
}

impl Connection {
    /// Waits for the next message of any partition. Cancel-safe: a message is
    /// taken from a consumer's queue only when its receive future completes.
    async fn receive(&mut self) -> Result<(Consumer, IncomingMessage), ReceiveError> {
        let count = self.consumers.len();
        let start = self.next % count;
        let receives = (0..count).map(|offset| {
            let index = (start + offset) % count;
            let consumer = &self.consumers[index];
            Box::pin(async move { (index, consumer.receive().await) })
        });
        let ((index, message), _, _) = select_all(receives).await;
        self.next = index + 1;
        let message = message.map_err(|error| ReceiveError::Retry(error.into()))?;
        Ok((self.consumers[index].clone(), message))
    }

    /// Closes the consumers. Deliveries still held fail to acknowledge from
    /// now on.
    async fn close(self) -> Result<(), BoxError> {
        self.closed.store(true, Ordering::Release);
        let mut result = Ok(());
        for consumer in self.consumers {
            if let Err(error) = consumer.close().await {
                result = Err(error.into());
            }
        }
        result
    }
}

impl<C: Decoder<Value: Clone + Send + Sync + 'static>> Source for PulsarSource<C> {
    type Message = PulsarMessage<C>;

    async fn receive(&mut self) -> Result<Receive<Self::Message>, ReceiveError> {
        if self.closed {
            return Ok(Receive::End);
        }
        if self.connection.is_none() {
            self.connection = Some(self.connect().await.map_err(ReceiveError::Fatal)?);
        }
        let connection = self.connection.as_mut().expect("connected source");
        let (consumer, message) = connection.receive().await?;
        let delivery = Delivery::new(consumer.topic(), &message).map_err(ReceiveError::Fatal)?;
        Ok(Receive::Message(PulsarMessage {
            ordering_key: ordering_key(self.config.subscription_type, &delivery),
            payload: delivery
                .payload
                .filter(|bytes| !(self.config.empty_payload_is_tombstone && bytes.is_empty())),
            key: delivery.key,
            properties: delivery.properties,
            event_time: delivery.event_time,
            metadata: delivery.metadata,
            codec: self.codec.clone(),
            acknowledgement: Acknowledgement {
                consumer,
                id: message.message_id,
                closed: connection.closed.clone(),
                retry: connection.ack_retry.clone(),
                _pulsar: self.pulsar.clone(),
            },
        }))
    }

    async fn close(&mut self) -> Result<(), BoxError> {
        if self.closed {
            return Ok(());
        }
        self.closed = true;
        match self.connection.take() {
            Some(connection) => connection.close().await,
            None => Ok(()),
        }
    }
}

/// The application fields and delivery facts of one received message.
struct Delivery {
    /// `None` when the producer marked the message value as null.
    payload: Option<Vec<u8>>,
    key: Option<Vec<u8>>,
    ordering_key: Option<Vec<u8>>,
    properties: HashMap<String, String>,
    event_time: Option<u64>,
    metadata: PulsarMetadata,
}

impl Delivery {
    /// Reads the per-message fields of a batched message from its single
    /// message metadata and those of any other message from the entry's
    /// metadata.
    fn new(topic: String, message: &IncomingMessage) -> Result<Self, BoxError> {
        let entry = &message.metadata;
        let (properties, key, key_b64_encoded, ordering_key, event_time, null_value) =
            match &message.single_metadata {
                Some(single) => (
                    &single.properties,
                    &single.partition_key,
                    single.partition_key_b64_encoded,
                    &single.ordering_key,
                    single.event_time,
                    single.null_value,
                ),
                None => (
                    &entry.properties,
                    &entry.partition_key,
                    entry.partition_key_b64_encoded,
                    &entry.ordering_key,
                    entry.event_time,
                    entry.null_value,
                ),
            };
        let key = key
            .as_ref()
            .map(|key| {
                if key_b64_encoded.unwrap_or(false) {
                    BASE64
                        .decode(key)
                        .context("Pulsar message key is not valid base64")
                } else {
                    Ok(key.as_bytes().to_vec())
                }
            })
            .transpose()?;
        Ok(Self {
            payload: (!null_value.unwrap_or(false)).then(|| message.payload.to_vec()),
            key,
            ordering_key: ordering_key.as_ref().map(|key| key.to_vec()),
            properties: properties
                .iter()
                .map(|property| (property.key.clone(), property.value.clone()))
                .collect(),
            event_time,
            metadata: PulsarMetadata {
                topic,
                message_id: message_id(&message.message_id),
                publish_time: entry.publish_time,
            },
        })
    }
}

fn message_id(id: &MessageId) -> PulsarMessageId {
    PulsarMessageId {
        ledger_id: id.ledger_id,
        entry_id: id.entry_id,
        partition: id.partition,
        batch_index: id.batch_index,
    }
}

/// The scope within which the broker delivers to one consumer in order.
///
/// Exclusive and Failover subscriptions deliver each topic partition in order.
/// Key_Shared delivers each ordering key, or message key when no ordering key is
/// set, in order. Shared subscriptions and keyless Key_Shared messages have no
/// ordering scope.
fn ordering_key(
    subscription_type: PulsarSubscriptionType,
    delivery: &Delivery,
) -> Option<OrderingKey> {
    let partition = OrderingKey::new(
        delivery.metadata.topic.as_str(),
        i64::from(delivery.metadata.message_id.partition),
    );
    match subscription_type {
        PulsarSubscriptionType::Exclusive | PulsarSubscriptionType::Failover => Some(partition),
        PulsarSubscriptionType::KeyShared => delivery
            .ordering_key
            .as_deref()
            .or(delivery.key.as_deref())
            .map(|key| partition.with_key(key)),
        PulsarSubscriptionType::Shared => None,
    }
}

/// What acknowledging one delivery needs.
struct Acknowledgement {
    consumer: Consumer,
    id: MessageId,
    closed: Arc<AtomicBool>,
    retry: Arc<RetryPolicy>,
    /// Keeps the client open while the delivery can acknowledge through it.
    _pulsar: Pulsar,
}

impl Acknowledgement {
    fn ensure_open(&self) -> Result<(), BoxError> {
        ensure!(
            !self.closed.load(Ordering::Acquire),
            Error::closed,
            "Pulsar source is closed"
        );
        Ok(())
    }
}

/// One delivery; dropping it leaves the broker message unacknowledged.
pub struct PulsarMessage<C> {
    ordering_key: Option<OrderingKey>,
    payload: Option<Vec<u8>>,
    key: Option<Vec<u8>>,
    properties: HashMap<String, String>,
    event_time: Option<u64>,
    metadata: PulsarMetadata,
    codec: Arc<C>,
    acknowledgement: Acknowledgement,
}

impl<C: Decoder<Value: Clone + Send + Sync + 'static>> SourceMessage for PulsarMessage<C> {
    type Item = PulsarRecord<C::Value>;
    type Raw = PulsarRecord<Vec<u8>>;

    fn decode(&self) -> Result<Self::Item, BoxError> {
        Ok(PulsarRecord {
            value: self
                .payload
                .as_deref()
                .map(|bytes| self.codec.decode(bytes))
                .transpose()?,
            key: self.key.clone(),
            properties: self.properties.clone(),
            event_time: self.event_time,
            metadata: self.metadata.clone(),
        })
    }

    fn raw(&self) -> Self::Raw {
        PulsarRecord {
            value: self.payload.clone(),
            key: self.key.clone(),
            properties: self.properties.clone(),
            event_time: self.event_time,
            metadata: self.metadata.clone(),
        }
    }

    /// Retries a failed acknowledgement under the source's `ack_retry`
    /// policy. Acknowledging a message again is harmless, and an attempt
    /// on a reconnected session succeeds for a message the broker
    /// redelivers.
    async fn ack(self) -> Result<(), BoxError> {
        let acknowledgement = &self.acknowledgement;
        let mut failures = 0;
        loop {
            acknowledgement.ensure_open()?;
            let Err(error) = acknowledgement.consumer.ack(acknowledgement.id).await else {
                return Ok(());
            };
            failures += 1;
            if failures >= acknowledgement.retry.max_attempts {
                return Err(Error::wrap(
                    format!("Pulsar acknowledgement failed after {failures} attempts"),
                    error,
                )
                .into());
            }
            tokio::time::sleep(acknowledgement.retry.delay(failures)).await;
        }
    }

    fn ordering_key(&self) -> Option<OrderingKey> {
        self.ordering_key.clone()
    }

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

#[cfg(test)]
mod tests {
    use super::*;
    use magnetar::proto::pb::{KeyValue, MessageMetadata, SingleMessageMetadata};
    use std::time::Instant;

    fn incoming(
        metadata: MessageMetadata,
        single: Option<SingleMessageMetadata>,
    ) -> IncomingMessage {
        let mut message_id = MessageId::EARLIEST;
        message_id.ledger_id = 7;
        message_id.entry_id = 3;
        message_id.partition = 1;
        if single.is_some() {
            message_id.batch_index = 0;
            message_id.batch_size = 1;
        }
        IncomingMessage {
            message_id,
            metadata: Arc::new(metadata),
            single_metadata: single,
            payload: Default::default(),
            redelivery_count: 0,
            broker_entry_metadata: None,
            arrived_at: Instant::now(),
        }
    }

    #[test]
    fn deliveries_decode_base64_keys_and_null_markers() {
        let metadata = MessageMetadata {
            partition_key: Some("AAEC/f7/".into()),
            partition_key_b64_encoded: Some(true),
            null_value: Some(true),
            publish_time: 41,
            ..MessageMetadata::default()
        };
        let delivery =
            Delivery::new("orders-partition-1".into(), &incoming(metadata, None)).unwrap();
        assert_eq!(delivery.key, Some(vec![0, 1, 2, 253, 254, 255]));
        assert_eq!(delivery.payload, None);
        assert_eq!(delivery.metadata.publish_time, 41);
        assert_eq!(
            delivery.metadata.message_id,
            PulsarMessageId {
                ledger_id: 7,
                entry_id: 3,
                partition: 1,
                batch_index: -1,
            }
        );
    }

    #[test]
    fn batched_deliveries_read_their_single_message_metadata() {
        let metadata = MessageMetadata {
            partition_key: Some("entry".into()),
            event_time: Some(1),
            ..MessageMetadata::default()
        };
        let single = SingleMessageMetadata {
            partition_key: Some("customer".into()),
            properties: vec![KeyValue {
                key: "kind".into(),
                value: "order".into(),
            }],
            event_time: Some(42),
            null_value: Some(true),
            ..SingleMessageMetadata::default()
        };
        let delivery = Delivery::new("orders".into(), &incoming(metadata, Some(single))).unwrap();
        assert_eq!(delivery.key.as_deref(), Some(b"customer".as_slice()));
        assert_eq!(delivery.event_time, Some(42));
        assert_eq!(
            delivery.properties.get("kind").map(String::as_str),
            Some("order")
        );
        assert_eq!(delivery.payload, None);
        assert_eq!(delivery.metadata.message_id.batch_index, 0);
    }

    fn delivery(key: Option<&[u8]>, ordering_key: Option<&[u8]>) -> Delivery {
        Delivery {
            payload: Some(vec![]),
            key: key.map(<[u8]>::to_vec),
            ordering_key: ordering_key.map(<[u8]>::to_vec),
            properties: HashMap::new(),
            event_time: None,
            metadata: PulsarMetadata {
                topic: "persistent://public/default/orders-partition-2".into(),
                message_id: PulsarMessageId {
                    ledger_id: 0,
                    entry_id: 0,
                    partition: 2,
                    batch_index: -1,
                },
                publish_time: 0,
            },
        }
    }

    #[test]
    fn ordering_scope_follows_the_subscription_type() {
        let partition = OrderingKey::new("persistent://public/default/orders-partition-2", 2);
        let delivery = delivery(Some(b"customer"), None);
        assert_eq!(
            ordering_key(PulsarSubscriptionType::Exclusive, &delivery),
            Some(partition.clone())
        );
        assert_eq!(
            ordering_key(PulsarSubscriptionType::Failover, &delivery),
            Some(partition.clone())
        );
        assert_eq!(
            ordering_key(PulsarSubscriptionType::Shared, &delivery),
            None
        );
        assert_eq!(
            ordering_key(PulsarSubscriptionType::KeyShared, &delivery),
            Some(partition.clone().with_key(b"customer".as_slice()))
        );
    }

    #[test]
    fn key_shared_prefers_the_ordering_key_and_ignores_keyless_messages() {
        let partition = OrderingKey::new("persistent://public/default/orders-partition-2", 2);
        assert_eq!(
            ordering_key(
                PulsarSubscriptionType::KeyShared,
                &delivery(Some(b"customer"), Some(b"order"))
            ),
            Some(partition.with_key(b"order".as_slice()))
        );
        assert_eq!(
            ordering_key(PulsarSubscriptionType::KeyShared, &delivery(None, None)),
            None
        );
    }
}