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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
//! The checks against the in-memory broker, and against doubles broken the way a broker's retry
//! path breaks, so each check stays proven to fail where it should.

use std::{
    convert::Infallible,
    future::{Future, ready},
    sync::{
        Arc, Mutex, OnceLock,
        atomic::{AtomicBool, Ordering},
    },
    time::Duration,
};

use futures::{Stream, StreamExt, stream};
use tokio::{runtime::Handle, sync::Mutex as AsyncMutex};

use super::{CONTROL, EXTRA_DELIVERIES, broker_moves, redelivery_address};
use crate::{
    AckError, AddressedCopies, BrokerMoves, BytesMut, DeclareRetryError, HeaderMap,
    IncomingMessage, Name, OutgoingMessage, Publisher, RedeliveryAddress, RedeliveryAddressed,
    RetryDeclaration, Subscribe, Subscriber, SubscriptionSource, Take,
    memory::{
        ConnectedMemoryBroker, MemoryBroker, MemoryError, MemoryMessage, MemoryPublisher,
        MemorySource, MemorySubscriber,
    },
    nonzero,
    runtime::RETRY_COUNT_HEADER,
};

// The factories stay closures throughout: their bounds are higher-ranked, which a method path
// does not satisfy.

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_memory_descriptor_passes() {
    redelivery_address(
        MemoryBroker::new,
        |name| MemorySource::new(name),
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_memory_bare_name_passes() {
    redelivery_address(
        MemoryBroker::new,
        |name| Name::new(name.to_owned()),
        |connected| connected.publisher(),
    )
    .await;
}

/// Two subscriptions sharing their deliveries are a group, and a copy reaching one of them is
/// what the check expects of one.
#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_group_that_shares_its_deliveries_passes() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Shared, Counting::Honest),
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "the copy never arrived")]
async fn an_address_that_reaches_nothing_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::Honest).misaddressed(),
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "exactly one consumer of a group gets a retry copy")]
async fn a_copy_that_reaches_every_member_of_a_group_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::SharedWithCopiesToAll, Counting::Honest),
        |connected| connected.publisher(),
    )
    .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "lost the header x-conformance-copy")]
async fn a_publisher_that_drops_headers_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| MemorySource::new(name),
        |connected| StripsHeaders(connected.publisher(), None),
    )
    .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "lost x-ruststream-retry-count")]
async fn a_publisher_that_drops_the_retry_count_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| MemorySource::new(name),
        |connected| StripsHeaders(connected.publisher(), Some(RETRY_COUNT_HEADER)),
    )
    .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "the copy never arrived")]
async fn a_publisher_that_sends_on_the_callers_runtime_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| MemorySource::new(name),
        |connected| SpawnsOnCaller(connected.publisher()),
    )
    .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(
    expected = "the control message published to the descriptor's subject never arrived"
)]
async fn a_publisher_bound_to_its_first_callers_runtime_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| MemorySource::new(name),
        |connected| AttachesOnFirstUse(connected.publisher(), OnceLock::new()),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "redelivery_count on the copy's first delivery must be 1")]
async fn a_count_from_zero_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::FromZero),
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "redelivery_count on a redelivery after nack(true) must be 2")]
async fn a_count_that_does_not_grow_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::Stuck),
        |connected| connected.publisher(),
    )
    .await;
}

/// A requeue that loses the headers leaves the runtime nothing to count the attempts with where the
/// transport reports no delivery count.
#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(
    expected = "the copy redelivered after nack(true) lost the header x-conformance-copy"
)]
async fn a_requeue_that_drops_the_headers_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| {
            Probe::new(name, Reading::Own, Counting::Silent).settling(Settling::RequeueDropsHeaders)
        },
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_broker_that_moves_at_the_cap_passes() {
    for attempts in [nonzero!(1u32), nonzero!(2u32), nonzero!(3u32)] {
        broker_moves(
            MemoryBroker::new,
            |name| Moves::new(name, Moving::AtCap),
            |connected| connected.publisher(),
            attempts,
        )
        .await;
    }
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "the message was delivered 3 times")]
async fn a_broker_that_ignores_the_declaration_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::Never),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "the message was delivered 3 times")]
async fn a_broker_that_moves_one_delivery_late_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::PastCap),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "opened its subscription")]
async fn a_broker_that_accepts_half_a_declaration_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::AcceptsHalves),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

/// A transport with no requeue answers `Unsupported`, and has no attempt to count.
#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_broker_without_requeue_passes() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::NoRequeue),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "must succeed or be unsupported, got: Broker")]
async fn a_broker_whose_requeue_fails_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::RequeueFails),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(
    expected = "redelivery_count on a delivery the broker counts against the cap must be 1"
)]
async fn a_broker_that_counts_from_zero_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::CountsFromZero),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

/// A transport that admits one reader of a subscription is checked with the one.
#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_descriptor_admitting_one_reader_passes() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Exclusive, Counting::Honest),
        |connected| connected.publisher(),
    )
    .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "publishing the retry copy to the reported address")]
async fn a_publisher_that_refuses_the_copy_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| MemorySource::new(name),
        |_connected| Refuses,
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "neither the control message nor the copy arrived")]
async fn a_descriptor_that_reads_nothing_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::Honest).deaf(),
        |connected| connected.publisher(),
    )
    .await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "each is published once")]
async fn a_publisher_that_sends_twice_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| MemorySource::new(name),
        |connected| Duplicates(connected.publisher()),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_copy_whose_requeue_is_unsupported_passes() {
    redelivery_address(
        MemoryBroker::new,
        |name| {
            Probe::new(name, Reading::Own, Counting::Honest).settling(Settling::RequeueUnsupported)
        },
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "nack(requeue = true) must succeed or be unsupported, got: Broker")]
async fn a_copy_whose_requeue_fails_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::Honest).settling(Settling::RequeueFails),
        |connected| connected.publisher(),
    )
    .await;
}

/// Waits the check's whole deadline for the redelivery, on a paused clock that moves at once.
#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(start_paused = true)]
#[should_panic(expected = "a copy requeued with nack(true) did not come back")]
async fn a_requeue_that_loses_the_copy_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::Honest).settling(Settling::RequeueLoses),
        |connected| connected.publisher(),
    )
    .await;
}

/// A log that rewinds to the requeued copy delivers the settled control message again first.
#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_requeue_that_rewinds_past_the_control_passes() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::Honest).settling(Settling::RequeueRewinds),
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(
    expected = "deliveries of the control message arrived and none of the requeued copy"
)]
async fn a_requeue_that_redelivers_only_the_control_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::Honest).settling(Settling::RequeueFloods),
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = ": ack must succeed or be unsupported, got: Broker")]
async fn a_failing_ack_fails() {
    redelivery_address(
        MemoryBroker::new,
        |name| Probe::new(name, Reading::Own, Counting::Honest).settling(Settling::AckFails),
        |connected| connected.publisher(),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "was refused")]
async fn a_broker_that_refuses_the_full_declaration_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::RefusesDeclaration),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "did not open")]
async fn a_broker_that_refuses_the_declared_subscription_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::RefusesSubscription),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "the message reached the dead-letter destination after 1 deliveries")]
async fn a_broker_that_moves_one_delivery_early_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::BeforeCap),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "it arrived again on the dead-letter destination")]
async fn a_broker_that_moves_twice_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::MovesTwice),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

#[allow(clippy::redundant_closure_for_method_calls)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic(expected = "it arrived again on the subscription")]
async fn a_broker_that_delivers_a_moved_message_again_fails() {
    broker_moves(
        MemoryBroker::new,
        |name| Moves::new(name, Moving::MovesAndRedelivers),
        |connected| connected.publisher(),
        nonzero!(2u32),
    )
    .await;
}

/// How a [`Probe`]'s subscriptions read, and where its copies go.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reading {
    /// Each subscription reads the name on its own, as the in-memory broker does.
    Own,
    /// The subscriptions of one descriptor share one reader, as a queue's consumers do.
    Shared,
    /// A group as above, whose reported address reaches every member: the defect of a stand-in
    /// that fans a publish out to competing consumers.
    SharedWithCopiesToAll,
    /// One subscription reads the name, and the descriptor refuses a second one, as a socket the
    /// first one bound does.
    Exclusive,
}

/// What a [`Probe`]'s deliveries report as their count.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Counting {
    Honest,
    /// One short on every delivery.
    FromZero,
    /// `1` on every delivery.
    Stuck,
    /// No count at all, the honest answer of a transport that counts nothing.
    Silent,
}

/// An addressed descriptor over the in-memory bus, broken on request.
#[derive(Clone)]
struct Probe {
    name: String,
    reading: Reading,
    counting: Counting,
    misaddressed: bool,
    /// Its subscriptions read a name nothing is published to.
    deaf: bool,
    settling: Settling,
    /// Whether an [`Reading::Exclusive`] descriptor's one subscription is taken.
    taken: Arc<AtomicBool>,
    /// The one reader every subscription of a sharing descriptor takes from, opened by the first.
    group: Arc<Mutex<Option<Arc<AsyncMutex<MemorySubscriber>>>>>,
}

impl Probe {
    fn new(name: &str, reading: Reading, counting: Counting) -> Self {
        Self {
            name: name.to_owned(),
            reading,
            counting,
            misaddressed: false,
            deaf: false,
            settling: Settling::Honest,
            taken: Arc::default(),
            group: Arc::default(),
        }
    }

    /// Reports an address no subscription reads.
    fn misaddressed(mut self) -> Self {
        self.misaddressed = true;
        self
    }

    /// Reads a name nothing is published to.
    fn deaf(mut self) -> Self {
        self.deaf = true;
        self
    }

    /// Settles its deliveries as `settling` says.
    fn settling(mut self, settling: Settling) -> Self {
        self.settling = settling;
        self
    }

    /// The name its subscriptions read.
    fn read(&self) -> String {
        if self.deaf {
            format!("{}.deaf", self.name)
        } else {
            self.name.clone()
        }
    }

    fn copies(&self) -> String {
        format!("{}.copies", self.name)
    }

    async fn group_reader(
        &self,
        connected: &ConnectedMemoryBroker,
    ) -> Result<Arc<AsyncMutex<MemorySubscriber>>, MemoryError> {
        let existing = self.group.lock().expect("probe group lock").clone();
        if let Some(existing) = existing {
            return Ok(existing);
        }
        let opened = Arc::new(AsyncMutex::new(
            Subscribe::subscribe(connected, &self.name).await?,
        ));
        let mut group = self.group.lock().expect("probe group lock");
        Ok(Arc::clone(group.get_or_insert(opened)))
    }
}

impl SubscriptionSource<ConnectedMemoryBroker> for Probe {
    type Subscriber = ProbeSubscriber;
    type Copies = AddressedCopies;

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

    async fn subscribe(
        self,
        connected: &ConnectedMemoryBroker,
    ) -> Result<ProbeSubscriber, MemoryError> {
        let (shared, own) = match self.reading {
            Reading::Own => (
                None,
                Some(Subscribe::subscribe(connected, &self.read()).await?),
            ),
            Reading::Exclusive => {
                if self.taken.swap(true, Ordering::SeqCst) {
                    return Err(MemoryError::ShutDown);
                }
                (
                    None,
                    Some(Subscribe::subscribe(connected, &self.name).await?),
                )
            }
            Reading::Shared => (Some(self.group_reader(connected).await?), None),
            Reading::SharedWithCopiesToAll => (
                Some(self.group_reader(connected).await?),
                Some(Subscribe::subscribe(connected, &self.copies()).await?),
            ),
        };
        Ok(ProbeSubscriber {
            shared,
            own,
            counting: self.counting,
            settling: self.settling,
            name: self.name,
            publisher: connected.publisher(),
        })
    }
}

impl RedeliveryAddressed<ConnectedMemoryBroker> for Probe {
    fn redelivery_address(
        &self,
        _connected: &ConnectedMemoryBroker,
    ) -> impl Future<Output = Result<RedeliveryAddress, MemoryError>> + Send {
        let address = if self.misaddressed {
            format!("{}.elsewhere", self.name)
        } else if self.reading == Reading::SharedWithCopiesToAll {
            self.copies()
        } else {
            self.name.clone()
        };
        ready(Ok(RedeliveryAddress::new(address)))
    }
}

struct ProbeSubscriber {
    shared: Option<Arc<AsyncMutex<MemorySubscriber>>>,
    own: Option<MemorySubscriber>,
    counting: Counting,
    settling: Settling,
    /// What the descriptor was built from, where a rewinding requeue publishes the control again.
    name: String,
    publisher: MemoryPublisher,
}

impl Subscriber for ProbeSubscriber {
    type Message = ProbeMessage;
    type Error = Infallible;

    fn stream(&mut self) -> impl Stream<Item = Result<ProbeMessage, Infallible>> + Send + '_ {
        let counting = self.counting;
        let settling = self.settling;
        let name = self.name.clone();
        let publisher = self.publisher.clone();
        let shared = stream::unfold(self.shared.clone(), async move |shared| {
            let group = shared.as_ref()?;
            let item = group.lock().await.stream().next().await;
            item.map(|item| (item, shared))
        });
        let own = self.own.as_mut().map_or_else(
            || stream::pending().right_stream(),
            |own| own.stream().left_stream(),
        );
        stream::select(shared, own).map(move |item| {
            item.map(|inner| ProbeMessage {
                inner,
                counting,
                settling,
                name: name.clone(),
                publisher: publisher.clone(),
            })
        })
    }
}

struct ProbeMessage {
    inner: MemoryMessage,
    counting: Counting,
    settling: Settling,
    name: String,
    publisher: MemoryPublisher,
}

/// What a [`Probe`] that forgets headers hands out on a redelivery.
static NO_HEADERS: HeaderMap = HeaderMap::new();

impl IncomingMessage for ProbeMessage {
    fn payload(&self) -> &[u8] {
        self.inner.payload()
    }

    fn headers(&self) -> &HeaderMap {
        if self.settling == Settling::RequeueDropsHeaders && self.inner.redelivery_count() > Some(1)
        {
            return &NO_HEADERS;
        }
        self.inner.headers()
    }

    fn redelivery_count(&self) -> Option<u64> {
        let count = self.inner.redelivery_count();
        match self.counting {
            Counting::Honest => count,
            Counting::FromZero => count.map(|count| count - 1),
            Counting::Stuck => count.map(|_| 1),
            Counting::Silent => None,
        }
    }

    async fn ack(self) -> Result<(), AckError> {
        if self.settling == Settling::AckFails {
            return Err(AckError::Broker("the ack was lost".into()));
        }
        self.inner.ack().await
    }

    async fn nack(self, requeue: bool) -> Result<(), AckError> {
        if !requeue {
            return self.inner.nack(false).await;
        }
        let control = |times: usize| async move {
            for _ in 0..times {
                self.publisher
                    .publish(OutgoingMessage::new(&self.name, CONTROL), None)
                    .await
                    .map_err(|err| AckError::Broker(Box::new(err)))?;
            }
            Ok::<(), AckError>(())
        };
        match self.settling {
            Settling::Honest | Settling::RequeueDropsHeaders | Settling::AckFails => {
                self.inner.nack(true).await
            }
            Settling::RequeueUnsupported => {
                self.inner.ack().await?;
                Err(AckError::Unsupported)
            }
            Settling::RequeueFails => Err(AckError::Broker("the requeue was lost".into())),
            Settling::RequeueLoses => self.inner.ack().await,
            Settling::RequeueRewinds => {
                control(1).await?;
                self.inner.nack(true).await
            }
            Settling::RequeueFloods => {
                control(EXTRA_DELIVERIES).await?;
                self.inner.ack().await
            }
        }
    }
}

/// How a [`Probe`]'s deliveries settle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Settling {
    Honest,
    /// A requeue answers `Unsupported`, as a transport with no requeue does.
    RequeueUnsupported,
    /// Every requeue fails.
    RequeueFails,
    /// A redelivery after a requeue arrives with no headers.
    RequeueDropsHeaders,
    /// A requeue answers `Ok` and the message never comes back.
    RequeueLoses,
    /// A requeue delivers the settled control message again before the copy, as a log that
    /// rewinds to a requeued record does.
    RequeueRewinds,
    /// A requeue delivers the control message again and again, and never the copy.
    RequeueFloods,
    /// Every acknowledgement fails.
    AckFails,
}

/// A publisher that fails every publish.
struct Refuses;

impl Publisher for Refuses {
    type Payload = Take;
    type Error = MemoryError;
    type Options = ();

    fn publish(
        &self,
        _msg: OutgoingMessage<'_, BytesMut>,
        _options: Option<&()>,
    ) -> impl Future<Output = Result<(), MemoryError>> + Send {
        ready(Err(MemoryError::ShutDown))
    }
}

/// A publisher that sends every message twice.
struct Duplicates(MemoryPublisher);

impl Publisher for Duplicates {
    type Payload = Take;
    type Error = MemoryError;
    type Options = ();

    async fn publish(
        &self,
        msg: OutgoingMessage<'_, BytesMut>,
        options: Option<&()>,
    ) -> Result<(), MemoryError> {
        let (name, payload, headers) = msg.into_parts();
        let twin = OutgoingMessage::produced(name, payload.clone()).with_headers(headers.clone());
        self.0.publish(twin, options).await?;
        self.0
            .publish(
                OutgoingMessage::produced(name, payload).with_headers(headers),
                options,
            )
            .await
    }
}

/// A publisher that drops one header, or every header, on the way to the bus.
struct StripsHeaders(MemoryPublisher, Option<&'static str>);

impl Publisher for StripsHeaders {
    type Payload = Take;
    type Error = MemoryError;
    type Options = ();

    async fn publish(
        &self,
        msg: OutgoingMessage<'_, BytesMut>,
        options: Option<&()>,
    ) -> Result<(), MemoryError> {
        let (name, payload, mut headers) = msg.into_parts();
        match self.1 {
            Some(dropped) => {
                headers.remove(dropped);
            }
            None => headers = HeaderMap::new(),
        }
        self.0
            .publish(
                OutgoingMessage::produced(name, payload).with_headers(headers),
                options,
            )
            .await
    }
}

/// A publisher that leaves the send to a task on whichever runtime called it, and reports success
/// at once: the defect a handler on a dedicated thread loses its retry copy to.
struct SpawnsOnCaller(MemoryPublisher);

impl Publisher for SpawnsOnCaller {
    type Payload = Take;
    type Error = MemoryError;
    type Options = ();

    fn publish(
        &self,
        msg: OutgoingMessage<'_, BytesMut>,
        _options: Option<&()>,
    ) -> impl Future<Output = Result<(), MemoryError>> + Send {
        let (name, payload, headers) = msg.into_parts();
        let name = name.to_owned();
        let publisher = self.0.clone();
        tokio::spawn(async move {
            // The task has not run by the time the caller's runtime stops.
            tokio::time::sleep(Duration::from_millis(50)).await;
            let copy = OutgoingMessage::produced(&name, payload).with_headers(headers);
            let _ = publisher.publish(copy, None).await;
        });
        ready(Ok(()))
    }
}

/// A publisher that attaches to the runtime of its first caller and sends from there afterwards:
/// the lazily attached socket that dies with the handler thread which first used it.
struct AttachesOnFirstUse(MemoryPublisher, OnceLock<Handle>);

impl Publisher for AttachesOnFirstUse {
    type Payload = Take;
    type Error = MemoryError;
    type Options = ();

    async fn publish(
        &self,
        msg: OutgoingMessage<'_, BytesMut>,
        options: Option<&()>,
    ) -> Result<(), MemoryError> {
        let Some(attached) = self.1.get() else {
            let _ = self.1.set(Handle::current());
            return self.0.publish(msg, options).await;
        };
        let (name, payload, headers) = msg.into_parts();
        let name = name.to_owned();
        let publisher = self.0.clone();
        // Handed to the attached runtime, which runs it only while it is alive.
        drop(attached.spawn(async move {
            let later = OutgoingMessage::produced(&name, payload).with_headers(headers);
            let _ = publisher.publish(later, None).await;
        }));
        Ok(())
    }
}

/// How a [`Moves`] broker applies a declaration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Moving {
    /// Moves the delivery that spends the cap, and refuses half a declaration.
    AtCap,
    /// Takes the declaration and applies none of it.
    Never,
    /// Moves one delivery after the cap.
    PastCap,
    /// Opens a subscription on half a declaration.
    AcceptsHalves,
    /// Moves at the cap, and counts one short.
    CountsFromZero,
    /// Answers a requeue with `Unsupported`, as a transport with no requeue does.
    NoRequeue,
    /// Fails every requeue.
    RequeueFails,
    /// Refuses the full declaration as well as its halves.
    RefusesDeclaration,
    /// Takes the full declaration and then refuses to open the subscription.
    RefusesSubscription,
    /// Moves one delivery before the cap.
    BeforeCap,
    /// Moves at the cap, into the dead-letter destination twice.
    MovesTwice,
    /// Moves at the cap, and delivers the message on the subscription again soon after.
    MovesAndRedelivers,
}

/// A descriptor over the in-memory bus whose broker moves a spent delivery itself.
#[derive(Clone)]
struct Moves {
    name: String,
    declared: RetryDeclaration,
    moving: Moving,
}

impl Moves {
    fn new(name: &str, moving: Moving) -> Self {
        Self {
            name: name.to_owned(),
            declared: RetryDeclaration::new(),
            moving,
        }
    }
}

impl SubscriptionSource<ConnectedMemoryBroker> for Moves {
    type Subscriber = MovesSubscriber;
    type Copies = BrokerMoves;

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

    async fn subscribe(
        self,
        connected: &ConnectedMemoryBroker,
    ) -> Result<MovesSubscriber, MemoryError> {
        let full = self.declared.max_attempts().is_some() && self.declared.dead_letter().is_some();
        if full && self.moving == Moving::RefusesSubscription {
            return Err(MemoryError::ShutDown);
        }
        let inner = Subscribe::subscribe(connected, &self.name).await?;
        let rule = match (self.declared.max_attempts(), self.declared.dead_letter()) {
            (Some(cap), Some(dead)) if self.moving != Moving::Never => {
                Some((u64::from(cap.get()), dead.to_owned()))
            }
            _ => None,
        };
        Ok(MovesSubscriber {
            inner,
            rule,
            publisher: connected.publisher(),
            moving: self.moving,
        })
    }

    fn declare_retry(mut self, declaration: &RetryDeclaration) -> Self {
        self.declared = declaration.clone();
        self
    }

    fn declare_retry_on(
        &self,
        _connected: &ConnectedMemoryBroker,
        declaration: &RetryDeclaration,
    ) -> Result<(), DeclareRetryError> {
        let half = declaration.max_attempts().is_some() != declaration.dead_letter().is_some();
        if (half && self.moving != Moving::AcceptsHalves)
            || self.moving == Moving::RefusesDeclaration
        {
            return Err(DeclareRetryError::Broker(
                "a dead-letter policy needs the cap and the destination together".into(),
            ));
        }
        Ok(())
    }
}

struct MovesSubscriber {
    inner: MemorySubscriber,
    rule: Option<(u64, String)>,
    publisher: MemoryPublisher,
    moving: Moving,
}

impl Subscriber for MovesSubscriber {
    type Message = MovesMessage;
    type Error = Infallible;

    fn stream(&mut self) -> impl Stream<Item = Result<MovesMessage, Infallible>> + Send + '_ {
        let Self {
            inner,
            rule,
            publisher,
            moving,
        } = self;
        let moving = *moving;
        inner.stream().map(move |item| {
            item.map(|inner| MovesMessage {
                inner,
                rule: rule.clone(),
                publisher: publisher.clone(),
                moving,
            })
        })
    }
}

struct MovesMessage {
    inner: MemoryMessage,
    rule: Option<(u64, String)>,
    publisher: MemoryPublisher,
    moving: Moving,
}

impl IncomingMessage for MovesMessage {
    fn payload(&self) -> &[u8] {
        self.inner.payload()
    }

    fn headers(&self) -> &HeaderMap {
        self.inner.headers()
    }

    fn redelivery_count(&self) -> Option<u64> {
        let count = self.inner.redelivery_count();
        if self.moving == Moving::CountsFromZero {
            count.map(|count| count - 1)
        } else {
            count
        }
    }

    fn ack(self) -> impl Future<Output = Result<(), AckError>> + Send {
        self.inner.ack()
    }

    async fn nack(self, requeue: bool) -> Result<(), AckError> {
        match self.moving {
            Moving::NoRequeue if requeue => return Err(AckError::Unsupported),
            Moving::RequeueFails if requeue => {
                return Err(AckError::Broker("the requeue was lost".into()));
            }
            _ => {}
        }
        if requeue && let Some((cap, dead)) = &self.rule {
            let count = self.inner.redelivery_count().unwrap_or(1);
            let spent = match self.moving {
                Moving::PastCap => count > *cap,
                Moving::BeforeCap => count + 1 >= *cap,
                _ => count >= *cap,
            };
            if spent {
                let moves = if self.moving == Moving::MovesTwice {
                    2
                } else {
                    1
                };
                for _ in 0..moves {
                    self.publisher
                        .publish(OutgoingMessage::new(dead, self.inner.payload()), None)
                        .await
                        .map_err(|err| AckError::Broker(Box::new(err)))?;
                }
                if self.moving == Moving::MovesAndRedelivers {
                    // Later than the move, so the dead letter is read first, and well within the
                    // quiet window the check reads after it.
                    return self.inner.nack_after(Duration::from_millis(100)).await;
                }
                return self.inner.ack().await;
            }
        }
        self.inner.nack(requeue).await
    }
}