ruststream 0.7.5

Async messaging framework for Rust: broker-agnostic traits, router, codecs, and a conformance harness for broker authors.
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! Driving the service under test, against services written without the `macros` feature. The test
//! bodies are the ones of `examples/testing_driving.rs`: the harness drives the same app whichever
//! way the service was declared.
//!
//! ```text
//! cargo test --example manual_testing_driving --no-default-features --features testing,memory,json
//! ```

// A plain build compiles the services; the tests that use them exist only in the test build.
#![cfg_attr(not(test), allow(dead_code, unused_imports))]

use ruststream::memory::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Deserialize, Serialize, schemars::JsonSchema)]
struct Order {
    id: u64,
}

// `#[outgoing(name = "orders")]` by hand: the type fixes its destination.
impl OutgoingDestination for Order {
    type Form = FixedName;

    const DESTINATION: &'static str = "orders";
}

impl MessageHeaders for Order {
    type Contract = NoHeaders;
}

mod broker {
    use std::error::Error;
    use std::future::{Future, ready};

    use ruststream::memory::prelude::*;
    use ruststream::testing::TestApp;

    use super::Order;

    struct Accept;

    impl Handle<Order> for Accept {
        fn handle(
            &self,
            order: &Order,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            let _ = order.id;
            ready(Ok(()))
        }
    }

    struct Archive;

    impl Handle<Order> for Archive {
        fn handle(
            &self,
            order: &Order,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            let _ = order.id;
            ready(Ok(()))
        }
    }

    /// Commands go through a plain broker; the archive keeps its history on a retaining one.
    fn app() -> impl App<State = ()> {
        RustStream::new(AppInfo::new("orders", "0.1.0"))
            .with_broker(MemoryBroker::new(), |b| {
                b.include(subscriber("orders", Accept).build());
            })
            .with_broker(
                MemoryBroker::retaining(Retention::Messages(nonzero!(1000))),
                |b| {
                    b.include(subscriber("orders", Archive).build());
                },
            )
    }

    // --8<-- [start:broker]
    #[tokio::test]
    async fn each_broker_is_addressed_by_its_type() -> Result<(), Box<dyn Error>> {
        let tb = TestApp::start(app()).await?;
        tb.broker::<MemoryBroker<Retaining>>()
            .message(&Order { id: 7 })
            .publish()
            .await?;

        tb.broker::<MemoryBroker<Retaining>>()
            .subscriber("orders")
            .assert_called_once();
        tb.broker::<MemoryBroker>()
            .subscriber("orders")
            .assert_not_called();
        Ok(())
    }
    // --8<-- [end:broker]
}

mod broker_named {
    use std::error::Error;
    use std::future::{Future, ready};

    use ruststream::memory::prelude::*;
    use ruststream::testing::TestApp;

    use super::Order;

    struct Accept;

    impl Handle<Order> for Accept {
        fn handle(
            &self,
            order: &Order,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            let _ = order.id;
            ready(Ok(()))
        }
    }

    /// One broker per region, both of the same type.
    fn app() -> impl App<State = ()> {
        RustStream::new(AppInfo::new("orders", "0.1.0"))
            .with_broker_labeled("eu", MemoryBroker::new(), |b| {
                b.include(subscriber("orders", Accept).build());
            })
            .with_broker_labeled("us", MemoryBroker::new(), |b| {
                b.include(subscriber("orders", Accept).build());
            })
    }

    // --8<-- [start:broker-named]
    #[tokio::test]
    async fn an_order_stays_in_its_region() -> Result<(), Box<dyn Error>> {
        let tb = TestApp::start(app()).await?;
        tb.broker_named("eu")
            .message(&Order { id: 7 })
            .publish()
            .await?;

        tb.broker_named("eu")
            .subscriber("orders")
            .assert_called_once()
            .with(&Order { id: 7 });
        tb.broker_named("us")
            .subscriber("orders")
            .assert_not_called();
        Ok(())
    }
    // --8<-- [end:broker-named]
}

mod message {
    use std::error::Error;
    use std::future::{Future, ready};

    use ruststream::memory::prelude::*;
    use ruststream::testing::TestApp;
    use serde::{Deserialize, Serialize};

    use super::Order;

    #[derive(Debug, PartialEq, Deserialize, Serialize, schemars::JsonSchema)]
    struct Refund {
        order_id: u64,
    }

    // `#[derive(Outgoing)]` with no `name`, by hand: whoever publishes it says where.
    impl OutgoingDestination for Refund {
        type Form = CallerName;
    }

    impl MessageHeaders for Refund {
        type Contract = NoHeaders;
    }

    struct Accept;

    impl Handle<Order> for Accept {
        fn handle(
            &self,
            order: &Order,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            let _ = order.id;
            ready(Ok(()))
        }
    }

    struct IssueRefund;

    impl Handle<Refund> for IssueRefund {
        fn handle(
            &self,
            refund: &Refund,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            let _ = refund.order_id;
            ready(Ok(()))
        }
    }

    fn app() -> impl App<State = ()> {
        RustStream::new(AppInfo::new("orders", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
            b.include(subscriber("orders", Accept).build());
            b.include(subscriber("refunds", IssueRefund).build());
        })
    }

    // --8<-- [start:message]
    #[tokio::test]
    async fn inputs_are_built_like_the_service_builds_its_own() -> Result<(), Box<dyn Error>> {
        let tb = TestApp::start(app()).await?;
        tb.message(&Order { id: 7 }).publish().await?;
        tb.broker::<MemoryBroker>()
            .message(&Refund { order_id: 7 })
            .to("refunds")
            .publish()
            .await?;

        let broker = tb.broker::<MemoryBroker>();
        broker
            .subscriber("orders")
            .assert_called_once()
            .with(&Order { id: 7 });
        broker
            .subscriber("refunds")
            .assert_called_once()
            .with(&Refund { order_id: 7 });
        Ok(())
    }
    // --8<-- [end:message]
}

mod publish {
    use std::error::Error;
    use std::future::{Future, ready};

    use ruststream::memory::prelude::*;
    use ruststream::testing::TestApp;
    use serde::{Deserialize, Serialize};

    use super::Order;

    #[derive(Debug, PartialEq, Deserialize, Serialize, schemars::JsonSchema)]
    struct Receipt {
        order_id: u64,
    }

    // `#[outgoing(name = "receipts")]` by hand: the type fixes its destination.
    impl OutgoingDestination for Receipt {
        type Form = FixedName;

        const DESTINATION: &'static str = "receipts";
    }

    impl MessageHeaders for Receipt {
        type Contract = NoHeaders;
    }

    struct IssueReceipt;

    impl Handle<Order, Receipt> for IssueReceipt {
        fn handle(
            &self,
            order: &Order,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<Receipt, HandlerOutcome>> {
            ready(Ok(Receipt { order_id: order.id }))
        }
    }

    struct FileReceipt;

    impl Handle<Receipt> for FileReceipt {
        fn handle(
            &self,
            receipt: &Receipt,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            let _ = receipt.order_id;
            ready(Ok(()))
        }
    }

    fn app() -> impl App<State = ()> {
        RustStream::new(AppInfo::new("orders", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
            b.include(subscriber("orders", IssueReceipt).reply().build())
                .out_reply(Publish);
            b.include(subscriber("receipts", FileReceipt).build());
        })
    }

    // --8<-- [start:publish]
    #[tokio::test]
    async fn the_whole_reaction_is_over_when_publish_returns() -> Result<(), Box<dyn Error>> {
        let tb = TestApp::start(app()).await?;
        tb.message(&Order { id: 7 }).publish().await?;

        tb.broker::<MemoryBroker>()
            .subscriber("receipts")
            .assert_called_once()
            .with(&Receipt { order_id: 7 })
            .settled(HandlerOutcome::ack());
        Ok(())
    }
    // --8<-- [end:publish]
}

mod publish_shortcuts {
    use std::error::Error;
    use std::future::{Future, ready};

    use ruststream::memory::prelude::*;
    use ruststream::testing::TestApp;
    use serde::{Deserialize, Serialize};
    use serde_json::json;

    use super::Order;

    /// The header contract of a tenant's order.
    #[derive(Debug, Deserialize, Serialize, schemars::JsonSchema)]
    struct Tenant {
        tenant: String,
    }

    struct Accept;

    impl Handle<Order> for Accept {
        fn handle(
            &self,
            order: &Order,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            let _ = order.id;
            ready(Ok(()))
        }
    }

    struct AcceptForTenant;

    impl Handle<Message<Tenant, Order>> for AcceptForTenant {
        fn handle(
            &self,
            order: &Message<Tenant, Order>,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            if order.headers.tenant.is_empty() {
                return ready(Err(HandlerOutcome::drop()));
            }
            ready(Ok(()))
        }
    }

    fn app() -> impl App<State = ()> {
        RustStream::new(AppInfo::new("orders", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
            b.include(subscriber("orders", Accept).build());
            b.include(subscriber("tenant-orders", AcceptForTenant).build());
        })
    }

    // --8<-- [start:publish-shortcuts]
    #[tokio::test]
    async fn any_serde_value_can_be_published() -> Result<(), Box<dyn Error>> {
        let tb = TestApp::start(app()).await?;
        tb.publish("orders", &json!({ "id": 7 })).await?;
        tb.broker::<MemoryBroker>()
            .publish_with_headers(
                "tenant-orders",
                &json!({ "id": 8 }),
                &Tenant {
                    tenant: "acme".to_owned(),
                },
            )
            .await?;

        let broker = tb.broker::<MemoryBroker>();
        broker
            .subscriber("orders")
            .assert_called_once()
            .with(&Order { id: 7 });
        broker
            .subscriber("tenant-orders")
            .assert_called_once()
            .settled(HandlerOutcome::ack());
        Ok(())
    }
    // --8<-- [end:publish-shortcuts]
}

mod settle {
    use std::error::Error;
    use std::future::{Future, ready};

    use ruststream::memory::prelude::*;
    use ruststream::testing::TestApp;

    use super::Order;

    struct AcceptAll;

    impl Handle<[Order]> for AcceptAll {
        fn handle(
            &self,
            orders: &[Order],
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), Vec<HandlerOutcome>>> {
            let _ = orders.len();
            ready(Ok(()))
        }
    }

    fn app(broker: MemoryBroker) -> impl App<State = ()> {
        RustStream::new(AppInfo::new("orders", "0.1.0")).with_broker(broker, |b| {
            b.include(subscriber("orders", AcceptAll).batch(nonzero!(8)).build());
        })
    }

    // --8<-- [start:settle]
    #[tokio::test]
    async fn two_orders_arrive_in_one_batch() -> Result<(), Box<dyn Error>> {
        let broker = MemoryBroker::new();
        let publisher = broker.publisher();
        let tb = TestApp::start(app(broker)).await?;
        for id in [1, 2] {
            publisher.message(&Order { id }).publish().await?;
        }
        tb.settle().await?;

        tb.broker::<MemoryBroker>()
            .subscriber("orders")
            .assert_called_once()
            .assert_batch_sizes(&[2]);
        Ok(())
    }
    // --8<-- [end:settle]
}

mod advance {
    use std::error::Error;
    use std::future::{Future, ready};
    use std::time::Duration;

    use ruststream::memory::prelude::*;
    use ruststream::testing::TestApp;
    use serde::{Deserialize, Serialize};

    const RECHECK: Duration = Duration::from_secs(5);

    #[derive(Debug, PartialEq, Deserialize, Serialize, schemars::JsonSchema)]
    struct Payment {
        id: u64,
        cleared: bool,
    }

    // `#[outgoing(name = "payments")]` by hand: the type fixes its destination.
    impl OutgoingDestination for Payment {
        type Form = FixedName;

        const DESTINATION: &'static str = "payments";
    }

    impl MessageHeaders for Payment {
        type Contract = NoHeaders;
    }

    struct Reconcile;

    impl Handle<Payment> for Reconcile {
        fn handle(
            &self,
            payment: &Payment,
            _outs: &(),
            _ctx: &mut Context<'_>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            if !payment.cleared {
                return ready(Err(HandlerOutcome::retry_after(RECHECK)));
            }
            ready(Ok(()))
        }
    }

    fn app() -> impl App<State = ()> {
        RustStream::new(AppInfo::new("payments", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
            b.include(subscriber("payments", Reconcile).build());
        })
    }

    // --8<-- [start:advance]
    #[tokio::test(start_paused = true)]
    async fn an_uncleared_payment_is_checked_again_later() -> Result<(), Box<dyn Error>> {
        let tb = TestApp::start(app()).await?;
        let payment = Payment {
            id: 7,
            cleared: false,
        };
        tb.message(&payment).publish().await?;
        tb.broker::<MemoryBroker>()
            .subscriber("payments")
            .assert_called_once()
            .settled(HandlerOutcome::retry_after(RECHECK));

        tb.advance(RECHECK).await?;
        tb.broker::<MemoryBroker>()
            .subscriber("payments")
            .assert_called(2)
            .with(&payment);
        Ok(())
    }
    // --8<-- [end:advance]
}

mod drain {
    use std::convert::Infallible;
    use std::error::Error;
    use std::future::{Future, ready};
    use std::sync::{Arc, Mutex};

    use ruststream::memory::prelude::*;
    use ruststream::testing::TestApp;

    use super::Order;

    /// Stands in for a mail client: each send is a network round trip.
    #[derive(Default)]
    struct Mailer {
        sent: Mutex<Vec<u64>>,
    }

    impl Mailer {
        async fn confirm(&self, order_id: u64) {
            tokio::task::yield_now().await;
            if let Ok(mut sent) = self.sent.lock() {
                sent.push(order_id);
            }
        }
    }

    struct Accept;

    impl Handle<Order, (), (), (), Arc<Mailer>> for Accept {
        fn handle(
            &self,
            order: &Order,
            _outs: &(),
            ctx: &mut Context<'_, (), Arc<Mailer>>,
        ) -> impl Future<Output = Result<(), HandlerOutcome>> {
            let mailer = Arc::clone(ctx.state());
            let order_id = order.id;
            // The confirmation goes out once the order is acknowledged, and never holds it back.
            ready(Err(HandlerOutcome::ack().and_after(async move {
                mailer.confirm(order_id).await;
            })))
        }
    }

    fn app() -> impl App<State = Arc<Mailer>> {
        RustStream::new(AppInfo::new("orders", "0.1.0"))
            .on_startup(async move |()| Ok::<_, Infallible>(Arc::new(Mailer::default())))
            .with_broker(MemoryBroker::new(), |b| {
                b.include(subscriber("orders", Accept).build());
            })
    }

    // --8<-- [start:drain]
    #[tokio::test]
    async fn the_confirmation_follows_the_ack() -> Result<(), Box<dyn Error>> {
        let mailer = Arc::new(Mailer::default());
        let tb = TestApp::with_state(app(), |_| Arc::clone(&mailer)).await?;
        tb.message(&Order { id: 7 }).publish().await?;
        tb.drain().await;

        let sent = mailer.sent.lock().map_err(|_| "a confirmation panicked")?;
        assert_eq!(*sent, [7]);
        Ok(())
    }
    // --8<-- [end:drain]
}

// The scenarios are the tests above; the command in the header runs them.
fn main() {}