ruststream-amqp 0.7.0

AMQP 1.0 broker implementation for the RustStream messaging framework (ActiveMQ Artemis, Azure Service Bus, RabbitMQ 4.x, and other AMQP 1.0 brokers).
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
//! [`AmqpAddress`]: the subscription descriptor.
//!
//! `AMQP` 1.0 standardises the wire but not the meaning of an address, so addressing stays
//! explicit: `queue` for anycast (competing consumers), `topic` for multicast (fan-out), and
//! `raw` for deployments with their own convention. The queue/topic constructors advertise the
//! matching terminus capability (`"queue"` / `"topic"`), which is how `ActiveMQ` Artemis and other
//! products disambiguate; `raw` sends the address verbatim with no capability.

use std::future::{Future, ready};
use std::num::NonZeroU32;
use std::time::Duration;

#[cfg(feature = "asyncapi")]
use ruststream::asyncapi::Bindings;
use ruststream::{
    AddressedCopies, RedeliveryAddress, RedeliveryAddressed, SubscriptionSource, nonzero,
};

#[cfg(feature = "asyncapi")]
use crate::bindings;

use crate::broker::ConnectedAmqpBroker;
use crate::error::AmqpError;
use crate::subscriber::AmqpSubscriber;

/// Default protocol-level credit (prefetch) granted to a subscription.
pub const DEFAULT_CREDIT: NonZeroU32 = nonzero!(256);

/// Default deadline closing a partial batch on a batch subscription.
pub const DEFAULT_BATCH_WAIT: Duration = Duration::from_millis(10);

/// Delivery guarantee of a subscription.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Settle {
    /// Deliveries are settled by the handler: `ack` accepts, `nack` releases or rejects. The
    /// default.
    #[default]
    AtLeastOnce,
    /// Deliveries are settled on receipt; `ack`/`nack` report
    /// [`AckError::Unsupported`](ruststream::AckError::Unsupported).
    AtMostOnce,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    Queue,
    Topic,
    Raw,
}

/// How the subscriptions on one address share its traffic: the terminus capability seen from the
/// consuming end.
///
/// This is the difference between a work queue and a broadcast, so the in-process transport
/// reproduces it instead of handing every message to everyone and hoping the deployment agrees.
#[cfg(feature = "testing")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Routing {
    /// Competing consumers: each message goes to exactly one of the subscriptions.
    Anycast,
    /// Fan-out: every subscription gets its own copy.
    Multicast,
}

/// A subscription descriptor for an `AMQP` 1.0 address.
///
/// Implements [`SubscriptionSource`], so it can sit inline in the `#[subscriber(..)]` decorator:
///
/// ```
/// # mod demo {
/// use ruststream_amqp::prelude::*;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Order {
///     id: u64,
/// }
///
/// #[subscriber(AmqpAddress::queue("orders").credit(nonzero!(64)))]
/// async fn fulfil(order: &Order) -> HandlerOutcome {
///     println!("fulfilling order {}", order.id);
///     HandlerOutcome::ack()
/// }
/// #
/// # #[ruststream::app]
/// # fn app() -> impl App {
/// #     RustStream::new(AppInfo::new("orders", "0.1.0"))
/// #         .with_broker(AmqpBroker::new("amqp://localhost:5672"), |b| {
/// #             b.include(fulfil);
/// #         })
/// # }
/// # }
/// # fn main() {}
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use]
pub struct AmqpAddress {
    address: String,
    kind: Kind,
    credit: NonZeroU32,
    settle: Settle,
    batch_wait: Duration,
}

impl AmqpAddress {
    fn of(address: String, kind: Kind) -> Self {
        Self {
            address,
            kind,
            credit: DEFAULT_CREDIT,
            settle: Settle::default(),
            batch_wait: DEFAULT_BATCH_WAIT,
        }
    }

    /// An anycast address: competing consumers, each message delivered to one of them.
    ///
    /// # Examples
    ///
    /// ```
    /// # mod demo {
    /// use ruststream_amqp::prelude::*;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Order {
    ///     id: u64,
    /// }
    ///
    /// // Every replica of the service competes for "orders": each order is handled once.
    /// #[subscriber(AmqpAddress::queue("orders"))]
    /// async fn fulfil(order: &Order) -> HandlerOutcome {
    ///     println!("fulfilling order {}", order.id);
    ///     HandlerOutcome::ack()
    /// }
    /// #
    /// # #[ruststream::app]
    /// # fn app() -> impl App {
    /// #     RustStream::new(AppInfo::new("orders", "0.1.0"))
    /// #         .with_broker(AmqpBroker::new("amqp://localhost:5672"), |b| {
    /// #             b.include(fulfil);
    /// #         })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    pub fn queue(name: impl Into<String>) -> Self {
        Self::of(name.into(), Kind::Queue)
    }

    /// A multicast address: fan-out, each message delivered to every subscriber.
    ///
    /// # Examples
    ///
    /// ```
    /// # mod demo {
    /// use ruststream_amqp::prelude::*;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Event {
    ///     kind: String,
    /// }
    ///
    /// // Every service subscribed to "events" gets its own copy of each event.
    /// #[subscriber(AmqpAddress::topic("events"))]
    /// async fn audit(event: &Event) -> HandlerOutcome {
    ///     println!("audit: {}", event.kind);
    ///     HandlerOutcome::ack()
    /// }
    /// #
    /// # #[ruststream::app]
    /// # fn app() -> impl App {
    /// #     RustStream::new(AppInfo::new("orders", "0.1.0"))
    /// #         .with_broker(AmqpBroker::new("amqp://localhost:5672"), |b| {
    /// #             b.include(audit);
    /// #         })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    pub fn topic(name: impl Into<String>) -> Self {
        Self::of(name.into(), Kind::Topic)
    }

    /// A verbatim address, for deployments with their own addressing convention
    /// (`"/queues/orders"` on `RabbitMQ` 4.x, a fully qualified queue on Artemis).
    ///
    /// # Examples
    ///
    /// ```
    /// # mod demo {
    /// use ruststream_amqp::prelude::*;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Order {
    ///     id: u64,
    /// }
    ///
    /// // RabbitMQ 4.x addresses a queue by its v2 path; the string reaches the broker as written.
    /// #[subscriber(AmqpAddress::raw("/queues/orders"))]
    /// async fn fulfil(order: &Order) -> HandlerOutcome {
    ///     println!("fulfilling order {}", order.id);
    ///     HandlerOutcome::ack()
    /// }
    /// #
    /// # #[ruststream::app]
    /// # fn app() -> impl App {
    /// #     RustStream::new(AppInfo::new("orders", "0.1.0"))
    /// #         .with_broker(AmqpBroker::new("amqp://localhost:5672"), |b| {
    /// #             b.include(fulfil);
    /// #         })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    pub fn raw(address: impl Into<String>) -> Self {
        Self::of(address.into(), Kind::Raw)
    }

    /// Sets the protocol-level credit (prefetch): how many unsettled deliveries the broker may
    /// have in flight to this subscription. Defaults to [`DEFAULT_CREDIT`].
    ///
    /// The count is a [`NonZeroU32`] because a subscription granted no credit receives nothing:
    /// zero is not a quieter setting but a stalled subscription, so it is unrepresentable here.
    ///
    /// # Examples
    ///
    /// ```
    /// # mod demo {
    /// use ruststream_amqp::prelude::*;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Order {
    ///     id: u64,
    /// }
    ///
    /// // At most 64 unsettled orders in flight to this service at once.
    /// #[subscriber(AmqpAddress::queue("orders").credit(nonzero!(64)))]
    /// async fn fulfil(order: &Order) -> HandlerOutcome {
    ///     println!("fulfilling order {}", order.id);
    ///     HandlerOutcome::ack()
    /// }
    /// #
    /// # #[ruststream::app]
    /// # fn app() -> impl App {
    /// #     RustStream::new(AppInfo::new("orders", "0.1.0"))
    /// #         .with_broker(AmqpBroker::new("amqp://localhost:5672"), |b| {
    /// #             b.include(fulfil);
    /// #         })
    /// # }
    /// # }
    /// # fn main() {}
    /// ```
    ///
    /// A zero is rejected while the service is compiled, not when the subscription opens:
    ///
    /// ```compile_fail
    /// use ruststream::nonzero;
    /// use ruststream_amqp::AmqpAddress;
    ///
    /// let source = AmqpAddress::queue("orders").credit(nonzero!(0));
    /// # let _ = source;
    /// ```
    pub fn credit(mut self, credit: NonZeroU32) -> Self {
        self.credit = credit;
        self
    }

    /// Sets the delivery guarantee. Defaults to [`Settle::AtLeastOnce`].
    pub fn settle(mut self, settle: Settle) -> Self {
        self.settle = settle;
        self
    }

    /// Caps how long a partial batch waits for more deliveries on a batch subscription, counted
    /// from its first one. Defaults to [`DEFAULT_BATCH_WAIT`].
    ///
    /// `AMQP` 1.0 has no batch pull, so the batches are assembled on the client and this deadline
    /// is what trades latency for fuller batches under a trickle of traffic. It has no effect on a
    /// single-message subscription, where every delivery goes out as it arrives.
    ///
    /// # Examples
    ///
    /// ```
    /// # mod demo {
    /// use std::time::Duration;
    ///
    /// use ruststream_amqp::prelude::*;
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Order {
    ///     id: u64,
    /// }
    ///
    /// // Up to 32 orders per call, or whatever arrived within 50 ms of the first one.
    /// #[subscriber(AmqpAddress::queue("orders").batch_wait(Duration::from_millis(50)))]
    /// async fn fulfil(orders: &[Order]) -> HandlerOutcome {
    ///     let ids: Vec<u64> = orders.iter().map(|order| order.id).collect();
    ///     println!("fulfilling orders {ids:?}");
    ///     HandlerOutcome::ack()
    /// }
    ///
    /// #[ruststream::app]
    /// fn app() -> impl App {
    ///     RustStream::new(AppInfo::new("orders", "0.1.0"))
    ///         .with_broker(AmqpBroker::new("amqp://localhost:5672"), |b| {
    ///             b.include(fulfil.batch(nonzero!(32)));
    ///         })
    /// }
    /// # }
    /// # fn main() {}
    /// ```
    pub fn batch_wait(mut self, batch_wait: Duration) -> Self {
        self.batch_wait = batch_wait;
        self
    }

    /// The address string sent to the broker.
    #[must_use]
    pub fn address(&self) -> &str {
        &self.address
    }

    pub(crate) fn credit_value(&self) -> u32 {
        self.credit.get()
    }

    pub(crate) fn settle_value(&self) -> Settle {
        self.settle
    }

    pub(crate) fn batch_wait_value(&self) -> Duration {
        self.batch_wait
    }

    /// Where a publisher on this broker reaches this subscription again.
    ///
    /// One `AMQP` 1.0 node serves both roles: a receiver attaches its source to the address, a
    /// sender its target. The address is therefore the answer for all three kinds, which is what
    /// lets the framework's deferred `retry_after` fallback work on this broker without native
    /// delayed redelivery. On a `queue` terminus the copy competes for consumers like any other
    /// message, and on a `topic` terminus every subscriber sees it: that is the terminus the
    /// declaration asked for, not a property of the retry.
    fn redelivery_target(&self) -> RedeliveryAddress {
        RedeliveryAddress::new(self.address.clone())
    }

    /// How this descriptor's terminus shares the address's traffic, for the in-process transport.
    ///
    /// `queue` competes, `topic` fans out. A `raw` address declares no capability, so on a server
    /// the peer's own configuration decides; in process there is no configuration to consult, and
    /// the transport delivers each message once rather than inventing a fan-out the deployment may
    /// not have. A service that wants the broadcast asserted says `topic`, which is also what the
    /// products needing the capability have to be told.
    #[cfg(feature = "testing")]
    pub(crate) fn routing(&self) -> Routing {
        match self.kind {
            Kind::Topic => Routing::Multicast,
            Kind::Queue | Kind::Raw => Routing::Anycast,
        }
    }

    /// The terminus capability this descriptor advertises, when one applies.
    pub(crate) fn capability(&self) -> Option<&'static str> {
        match self.kind {
            Kind::Queue => Some("queue"),
            Kind::Topic => Some("topic"),
            Kind::Raw => None,
        }
    }

    /// What this subscription tells a reader of the generated document: the node it reads, the
    /// terminus it asked for, and the link it reads over.
    ///
    /// The answer does not depend on the transport, so a document built from a test says what the
    /// deployment's does.
    #[cfg(feature = "asyncapi")]
    fn describe_channel(&self) -> Bindings {
        bindings::channel(
            &self.address,
            self.capability(),
            self.credit.get(),
            self.settle,
        )
    }

    /// Rejects descriptors that cannot form a subscription, before any I/O.
    ///
    /// Only the address is checked here: the credit is a [`NonZeroU32`], so an unusable one
    /// cannot reach this point.
    pub(crate) fn validate(&self) -> Result<(), AmqpError> {
        if self.address.is_empty() {
            return Err(AmqpError::InvalidAddress(
                "address must be non-empty".into(),
            ));
        }
        Ok(())
    }
}

impl SubscriptionSource<ConnectedAmqpBroker> for AmqpAddress {
    type Subscriber = AmqpSubscriber;

    /// `AMQP` 1.0 has no delayed redelivery and no wire-level way to declare a node with a
    /// delivery limit and a dead-letter address, so a spent delivery is this process's to move:
    /// the runtime publishes the copies and this descriptor says where they land.
    type Copies = AddressedCopies;

    fn name(&self) -> &str {
        self.address()
    }

    async fn subscribe(self, connected: &ConnectedAmqpBroker) -> Result<AmqpSubscriber, AmqpError> {
        connected.subscribe_address(self).await
    }

    #[cfg(feature = "asyncapi")]
    fn channel_bindings(&self) -> Bindings {
        self.describe_channel()
    }
}

impl RedeliveryAddressed<ConnectedAmqpBroker> for AmqpAddress {
    // The answer is the descriptor's own address, so nothing is asked of the connection and the
    // call needs no state machine.
    fn redelivery_address(
        &self,
        _connected: &ConnectedAmqpBroker,
    ) -> impl Future<Output = Result<RedeliveryAddress, AmqpError>> + Send {
        ready(Ok(self.redelivery_target()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_address_is_rejected_before_io() {
        assert!(matches!(
            AmqpAddress::queue("").validate(),
            Err(AmqpError::InvalidAddress(_))
        ));
    }

    /// `credit(0)` does not compile: `nonzero!(0)` fails const evaluation, and a runtime zero
    /// cannot be built either. What is left to pin is that the default is the one that applies.
    #[test]
    fn the_credit_defaults_and_takes_an_override() {
        assert_eq!(AmqpAddress::queue("orders").credit_value(), 256);
        assert_eq!(
            AmqpAddress::queue("orders")
                .credit(nonzero!(64))
                .credit_value(),
            64
        );
    }

    #[test]
    fn the_batch_deadline_defaults_and_takes_an_override() {
        assert_eq!(
            AmqpAddress::queue("q").batch_wait_value(),
            DEFAULT_BATCH_WAIT
        );
        assert_eq!(
            AmqpAddress::queue("q")
                .batch_wait(Duration::from_millis(50))
                .batch_wait_value(),
            Duration::from_millis(50)
        );
    }

    #[test]
    fn constructors_pick_the_matching_capability() {
        assert_eq!(AmqpAddress::queue("q").capability(), Some("queue"));
        assert_eq!(AmqpAddress::topic("t").capability(), Some("topic"));
        assert_eq!(AmqpAddress::raw("/queues/q").capability(), None);
    }
}