ruststream 0.7.2

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
//! Router parity: every definition form the broker scope mounts is reachable from a standalone
//! [`Router`], through the same form-token dispatch.
//!
//! The scope's own coverage of these forms lives next to each feature (`out_injection`,
//! `out_slots`, `seek_api`, ...); what is asserted here is that the router surface reaches them
//! too, with the terminals a consuming builder needs.
#![cfg(all(
    feature = "memory",
    feature = "macros",
    feature = "json",
    feature = "testing"
))]

mod common;

use common::{Event, Wire};

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

/// The payload view the byte-level bodies below take: the delivery's bytes, borrowed.
#[derive(Deserialized)]
struct Frame<'a>(&'a [u8]);

/// The reply those bodies return: its bytes leave on the wire as they are, at the subject the
/// mount site names.
#[derive(Outgoing, Serialized)]
struct Export(Vec<u8>);

// Out slots: the single-slot shorthand, named slots, and the batch counterpart.

#[subscriber("rp.out.in")]
async fn forward(event: &Event, Out(out): Out<impl Publisher>) -> HandlerOutcome {
    if out
        .message(event)
        .to("rp.out.forwarded")
        .publish()
        .await
        .is_err()
    {
        return HandlerOutcome::retry();
    }
    HandlerOutcome::ack()
}

/// The one-slot shorthand on a router: `.out(DefaultSlot, policy)` binds the unnamed slot, and
/// `.build()` commits.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_mounts_a_single_out_slot() {
    let router = Router::<MemoryBroker>::new()
        .include(forward)
        .out(DefaultSlot, Publish)
        .build();
    let app = RustStream::new(AppInfo::new("rp-out", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Event { id: 3 })
        .to("rp.out.in")
        .publish()
        .await
        .expect("publish");

    tb.broker::<MemoryBroker>()
        .published::<Event>("rp.out.forwarded")
        .assert_called_once()
        .with(&Event { id: 3 });
}

#[derive(OutSlot)]
#[publishes(Wire)]
struct Encoded;

#[derive(OutSlot)]
#[publishes(Wire)]
struct Audit;

#[subscriber("rp.slots.in")]
async fn transcode(
    chunk: &Frame<'_>,
    Out(encoded): Out<impl Publisher, Encoded>,
    Out(audit): Out<impl Publisher, Audit>,
) -> HandlerOutcome {
    if encoded
        .message(&Wire::of(chunk.0))
        .to("rp.slots.encoded")
        .publish()
        .await
        .is_err()
    {
        return HandlerOutcome::retry();
    }
    let receipt = chunk.0.len().to_be_bytes();
    if audit
        .message(&Wire::of(receipt))
        .to("rp.slots.audit")
        .publish()
        .await
        .is_err()
    {
        return HandlerOutcome::retry();
    }
    HandlerOutcome::ack()
}

/// Named slots bind by marker in any order, and `.build()` is the terminal.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_binds_named_out_slots_by_marker() {
    // Deliberately bound in the opposite of the signature order.
    let router = Router::<MemoryBroker>::new()
        .include(transcode)
        .out(Audit, Publish)
        .out(Encoded, Publish)
        .build();
    let app = RustStream::new(AppInfo::new("rp-slots", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Wire::of(b"frame"))
        .to("rp.slots.in")
        .publish()
        .await
        .expect("publish");

    tb.out::<Encoded>().assert_called_once().with_raw(b"frame");
    tb.out::<Audit>().assert_called_once();
}

/// A serialized dictionary member the slot's typed entry publishes byte-for-byte, the scope
/// counterpart being `tests/lanes.rs`.
#[derive(Outgoing, Serialized)]
#[outgoing(name = "rp.wire.out")]
struct WireCopy(Vec<u8>);

#[derive(OutSlot)]
#[publishes(WireCopy)]
struct Wires;

#[subscriber("rp.wire.in")]
async fn copy_out(frame: &Frame<'_>, Out(out): Out<impl Publisher, Wires>) -> HandlerOutcome {
    if out
        .message(&WireCopy(frame.0.to_vec()))
        .publish()
        .await
        .is_err()
    {
        return HandlerOutcome::retry();
    }
    HandlerOutcome::ack()
}

/// The serialized wire of a slot's typed entry mounts from a router exactly as from the scope:
/// the bytes leave as they are, at the destination the type declares.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_publishes_a_serialized_message_through_a_slot() {
    let router = Router::<MemoryBroker>::new()
        .include(copy_out)
        .out(Wires, Publish)
        .build();
    let app = RustStream::new(AppInfo::new("rp-wire", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Wire::of(b"frame"))
        .to("rp.wire.in")
        .publish()
        .await
        .expect("publish");
    tb.settle().await.expect("settle");

    tb.out::<Wires>().assert_called_once().with_raw(b"frame");
    tb.broker::<MemoryBroker>()
        .published::<WireCopy>("rp.wire.out")
        .assert_called_once()
        .with_raw(b"frame");
}

#[subscriber("rp.batch.in")]
async fn forward_batch(events: &[Event], Out(out): Out<impl Publisher>) -> HandlerOutcome {
    for event in events {
        if out
            .message(event)
            .to("rp.batch.forwarded")
            .publish()
            .await
            .is_err()
        {
            return HandlerOutcome::retry();
        }
    }
    HandlerOutcome::ack()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_mounts_a_batch_out_slot() {
    let router = Router::<MemoryBroker>::new()
        .include(forward_batch.batch(nonzero!(64)))
        .out(DefaultSlot, Publish)
        .build();
    let app = RustStream::new(AppInfo::new("rp-batch", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Event { id: 9 })
        .to("rp.batch.in")
        .publish()
        .await
        .expect("publish");

    tb.broker::<MemoryBroker>()
        .published::<Event>("rp.batch.forwarded")
        .assert_called_once()
        .with(&Event { id: 9 });
}

// A broker context key: the seek handle rides the delivery context, read by the Ctx extractor.

#[subscriber(MemorySource::new("rp.seek.in"))]
async fn rewind(event: &Event, Ctx(seeker): Ctx<SeekHandle>) -> HandlerOutcome {
    if event.id == 0 && seeker.seek(MemoryPosition::start()).await.is_err() {
        return HandlerOutcome::retry();
    }
    HandlerOutcome::ack()
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_mounts_a_seek_key_reader() {
    // A seek key needs a log to reposition over, so this router mounts on a retaining broker.
    let router = Router::<MemoryBroker<Retaining>>::new().include(rewind);
    let app = RustStream::new(AppInfo::new("rp-seek", "0.1.0")).with_broker(
        MemoryBroker::retaining(Retention::Messages(nonzero!(32))),
        |b| b.include_router(router),
    );
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker<Retaining>>()
        .message(&Event { id: 1 })
        .to("rp.seek.in")
        .publish()
        .await
        .expect("publish");
    tb.settle().await.expect("settle");
    tb.broker::<MemoryBroker<Retaining>>()
        .subscriber("rp.seek.in")
        .assert_called_once();
}

// The reply terminals: `.build()` takes the broker's default publish policy, on the encoded and
// the byte-for-byte form alike.

#[subscriber("rp.reply.in", reply("rp.reply.out"))]
async fn relay(event: &Event) -> Event {
    Event { id: event.id + 1 }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_defaults_the_reply_publisher_on_mount() {
    let router = Router::<MemoryBroker>::new().include(relay).build();
    let app = RustStream::new(AppInfo::new("rp-reply", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Event { id: 1 })
        .to("rp.reply.in")
        .publish()
        .await
        .expect("publish");
    tb.broker::<MemoryBroker>()
        .published::<Event>("rp.reply.out")
        .assert_called_once()
        .with(&Event { id: 2 });
}

#[subscriber("rp.raw.in", reply("rp.raw.out"))]
async fn echo_frame(frame: &Frame<'_>) -> Export {
    Export(frame.0.to_vec())
}

/// The byte-reply form: its reply leaves unencoded, so it is its own route on a router.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_mounts_the_byte_reply_form() {
    let router = Router::<MemoryBroker>::new().include(echo_frame).build();
    let app = RustStream::new(AppInfo::new("rp-raw", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Wire::of(b"frame"))
        .to("rp.raw.in")
        .publish()
        .await
        .expect("publish");
    tb.settle().await.expect("settle");

    tb.broker::<MemoryBroker>()
        .published::<Export>("rp.raw.out")
        .assert_called_once()
        .with_raw(b"frame");
}

// The two-attachment forms: a reply next to Out slots, single and batch.

#[subscriber("rp.gate.in", reply("rp.gate.reply"))]
async fn gate(event: &Event, Out(out): Out<impl Publisher>) -> Result<Event, HandlerOutcome> {
    if out
        .message(event)
        .to("rp.gate.audit")
        .publish()
        .await
        .is_err()
    {
        return Err(HandlerOutcome::retry());
    }
    Ok(Event { id: event.id + 1 })
}

/// The reply side defaults while the slot side is bound explicitly.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_composes_a_default_reply_with_out_slots() {
    let router = Router::<MemoryBroker>::new()
        .include(gate)
        .out(DefaultSlot, Publish)
        .build();
    let app = RustStream::new(AppInfo::new("rp-gate", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Event { id: 7 })
        .to("rp.gate.in")
        .publish()
        .await
        .expect("publish");

    tb.broker::<MemoryBroker>()
        .published::<Event>("rp.gate.audit")
        .assert_called_once()
        .with(&Event { id: 7 });
    tb.broker::<MemoryBroker>()
        .published::<Event>("rp.gate.reply")
        .assert_called_once()
        .with(&Event { id: 8 });
}

#[subscriber("rp.audit.in", reply("rp.audit.out"))]
async fn audited_relay(frame: &Frame<'_>, Out(audit): Out<impl Publisher>) -> Export {
    audit
        .message(&Wire::of(frame.0))
        .to("rp.audit.copy")
        .publish()
        .await
        .expect("the slot publisher is live");
    Export(frame.0.to_vec())
}

/// The byte-reply form with an `Out` slot, reply side defaulted.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_composes_a_byte_reply_with_out_slots() {
    let router = Router::<MemoryBroker>::new()
        .include(audited_relay)
        .out(DefaultSlot, Publish)
        .build();
    let app = RustStream::new(AppInfo::new("rp-audit", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Wire::of(b"frame"))
        .to("rp.audit.in")
        .publish()
        .await
        .expect("publish");
    tb.settle().await.expect("settle");

    tb.broker::<MemoryBroker>()
        .published::<Export>("rp.audit.out")
        .assert_called_once()
        .with_raw(b"frame");
    tb.broker::<MemoryBroker>()
        .published::<Export>("rp.audit.copy")
        .assert_called_once()
        .with_raw(b"frame");
}

#[subscriber("rp.ledger.in", reply("rp.ledger.receipts"))]
async fn settle_batch(
    events: &[Event],
    Out(out): Out<impl Publisher>,
) -> Result<Vec<Event>, HandlerOutcome> {
    let batch = Event {
        id: u64::try_from(events.len()).expect("a batch fits in u64"),
    };
    if out
        .message(&batch)
        .to("rp.ledger.batches")
        .publish()
        .await
        .is_err()
    {
        return Err(HandlerOutcome::retry());
    }
    Ok(events
        .iter()
        .map(|event| Event { id: event.id + 100 })
        .collect())
}

/// The batch two-attachment form, with the reply side named explicitly this time.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_composes_a_batch_reply_with_out_slots() {
    let router = Router::<MemoryBroker>::new()
        .include(settle_batch.batch(nonzero!(64)))
        .out(Reply, Publish)
        .out(DefaultSlot, Publish)
        .build();
    let app = RustStream::new(AppInfo::new("rp-ledger", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Event { id: 7 })
        .to("rp.ledger.in")
        .publish()
        .await
        .expect("publish");

    tb.broker::<MemoryBroker>()
        .published::<Event>("rp.ledger.receipts")
        .assert_called_once()
        .with(&Event { id: 107 });
    tb.broker::<MemoryBroker>()
        .published::<Event>("rp.ledger.batches")
        .assert_called_once()
        .with(&Event { id: 1 });
}

// Cross-broker tokens reach a router include site, exactly as they reach a scope's.

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_accepts_a_cross_broker_bind_token() {
    let egress_broker = MemoryBroker::new().bindable();
    let egress = egress_broker.bind(Publish);

    // The token names its own broker, so the registration order of the two scopes is irrelevant:
    // the slot pairs against the egress broker while the subscription lives on the ingress one.
    let router = Router::<MemoryBroker>::new()
        .include(forward)
        .out(DefaultSlot, egress)
        .build();
    let app = RustStream::new(AppInfo::new("rp-bridge", "0.1.0"))
        .with_broker_labeled("ingress", MemoryBroker::new(), |b| b.include_router(router))
        .with_broker_labeled("egress", egress_broker, |_b| {});
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker_named("ingress")
        .message(&Event { id: 5 })
        .to("rp.out.in")
        .publish()
        .await
        .expect("publish");
    tb.broker_named("egress")
        .published::<Event>("rp.out.forwarded")
        .assert_called_once()
        .with(&Event { id: 5 });
}

// The batch reply terminal, and the metadata every new route kind contributes.

#[subscriber("rp.batch.in", reply("rp.batch.out"))]
async fn bulk_relay(events: &[Event]) -> Vec<Event> {
    events
        .iter()
        .map(|event| Event { id: event.id + 1 })
        .collect()
}

/// A batch publishing form mounted with only its batch size takes the broker's own default
/// publish policy: naming the size seals the definition, so the reply wiring defaults.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_router_defaults_the_batch_reply_publisher_on_mount() {
    let router = Router::<MemoryBroker>::new()
        .include(bulk_relay.batch(nonzero!(64)))
        .build();
    let app = RustStream::new(AppInfo::new("rp-batch", "0.1.0"))
        .with_broker(MemoryBroker::new(), |b| b.include_router(router));
    let tb = TestApp::start(app).await.expect("harness start");

    tb.broker::<MemoryBroker>()
        .message(&Event { id: 1 })
        .to("rp.batch.in")
        .publish()
        .await
        .expect("publish");

    tb.broker::<MemoryBroker>()
        .published::<Event>("rp.batch.out")
        .assert_called_once()
        .with(&Event { id: 2 });
}

/// Every route kind contributes its registration metadata, in registration order: that list is
/// what the `AsyncAPI` document is generated from.
#[test]
fn every_new_route_kind_reports_its_metadata_in_registration_order() {
    let router = Router::<MemoryBroker>::new()
        .include(rewind)
        .include(echo_frame)
        .build()
        .include(relay)
        .build()
        .include(bulk_relay.batch(nonzero!(64)))
        .build()
        .include(forward)
        .out(DefaultSlot, Publish)
        .build()
        .include(forward_batch.batch(nonzero!(64)))
        .out(DefaultSlot, Publish)
        .build();

    let names: Vec<_> = router.handlers().into_iter().map(|m| m.name).collect();
    assert_eq!(
        names,
        [
            "rp.seek.in",
            "rp.raw.in",
            "rp.reply.in",
            "rp.batch.in",
            "rp.out.in",
            "rp.batch.in",
        ]
    );
}