ulo-rpc-conformance 0.1.0-alpha.3

The conformance suite every Ulo RPC link runs
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
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
//! Scenarios: deadlines.

use std::error::Error as _;
use std::future::{Future, IntoFuture};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use std::time::{Duration, Instant};

use futures_util::StreamExt;

use ulo::{AppHandle, Bound, BoundAddr, BoxError, CancelReason, ExecOptions, ExecutionRef, Runtime, Timer};
use ulo_rpc::{CallHeaders, Capabilities, Frame, Link, Outbound, Subscription, RpcClient, RpcError, RpcStream, ZeroTimeout};
use ulo_rpc::link::Inbound;
use ulo_transport::{Count, ErrorKind};

use crate::{Broker, Budget};
use crate::cases::app::{
    ADD, Add, COUNT, DEADLINE, DEADLINE_STREAM, DEADLINE_SUM, EVENT, Fixture, Mounts, PAUSE, STALL, SUM, Sum, TICKS, addresses,
    client_over, client_timed, eventually, failed, refused_at_startup, streams, within,
};

/// `deadline-ms` fires `Deadline` and renders `timeout`: a call whose `req` carries 300 ms, written
/// by a [`Stamped`] link below a client waiting ten seconds, is answered the server's `timeout`
/// within five seconds, and its handler is ended `Deadline`.
pub async fn deadline_ms<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    let link = Stamped { link: fixture.broker.client_link(&addresses(&[&fixture.server])), value: "300" };
    let client = client_over::<B, _>(link).await;
    let started = Instant::now();
    let outcome = client.rpc.request::<_, ()>(STALL, &()).timeout(Duration::from_secs(10)).await;
    failed(outcome, ErrorKind::Timeout);
    assert!(started.elapsed() < Duration::from_secs(5), "the call was answered after {:?}, at the client's timeout rather than the server's", started.elapsed());
    let probe = fixture.server.probe.clone();
    let settle = fixture.broker.budget().settle;
    assert!(eventually::<B>(settle, || probe.stalled().is_some()).await, "the stalled handler was not ended");
    assert_eq!(probe.stalled(), Some(Some(CancelReason::Deadline)));
    client.close().await;
    fixture.stop().await;
}

/// The client's own timeout, as `Timeout`.
pub async fn client_timeout<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    let started = Instant::now();
    let outcome = fixture.rpc().request::<_, ()>(STALL, &()).timeout(Duration::from_millis(300)).await;
    failed(outcome, ErrorKind::Timeout);
    assert!(started.elapsed() < Duration::from_secs(3), "the client's timeout took {:?}", started.elapsed());
    fixture.stop().await;
}

/// A call given a 300 ms timeout carries it as its deadline, and the server ends the call there.
/// The call goes through a client link that never sends a `cancel`, so the timeout's `cancel`
/// does not reach the server and only the deadline the call carried can end it.
pub async fn timeout_is_the_server_s_deadline<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    let link = MutedCancel(fixture.broker.client_link(&addresses(&[&fixture.server])));
    let client = client_over::<B, _>(link).await;
    let started = Instant::now();
    let outcome = client.rpc.request::<_, ()>(STALL, &()).timeout(Duration::from_millis(300)).await;
    failed(outcome, ErrorKind::Timeout);
    let probe = fixture.server.probe.clone();
    let settle = fixture.broker.budget().settle;
    assert!(
        eventually::<B>(Duration::from_millis(300) + settle, || probe.stalled().is_some()).await,
        "the stalled handler was still running {:?} after a call with a 300 ms timeout began",
        started.elapsed()
    );
    assert_eq!(probe.stalled(), Some(Some(CancelReason::Deadline)), "what ended the stalled handler");
    client.close().await;
    fixture.stop().await;
}

/// The idle timeout the stream-deadline scenarios set, the unit their other bounds are written in:
/// the broker's settle budget, the time a frame takes to cross it, 500 ms at the default budget.
/// Each scenario asserts the order of its events, not their spacing, so its bounds grow with the
/// broker's latency and are otherwise short.
fn idle_of(budget: Budget) -> Duration {
    budget.settle
}

/// How long the scenarios below hold a stream silent between its two items: four idle timeouts,
/// two seconds at the default budget.
fn silence_of(budget: Budget) -> Duration {
    idle_of(budget) * 4
}

/// A stream's idle timeout bounds each silence and not the whole call: a stream read with an
/// idle timeout of the broker's settle budget, its ticks 20 ms apart, keeps yielding for three
/// idle timeouts.
pub async fn stream_idle_timeout_is_per_frame<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    if !streams(&fixture.capabilities()) {
        refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
        return fixture.stop().await;
    }
    let idle = idle_of(fixture.broker.budget());
    let mut ticks = fixture.rpc().stream::<_, u64>(TICKS, &()).idle_timeout(Bound::After(idle)).await.expect("the stream opens");
    let opened = Instant::now();
    while opened.elapsed() < idle * 3 {
        let tick = within::<B, _>(Duration::from_secs(10), "a tick", ticks.next()).await.expect("the stream yields");
        if let Err(error) = tick {
            panic!("the stream failed {:?} after it opened, its idle timeout {idle:?}: {error:?}", opened.elapsed());
        }
    }
    drop(ticks);
    fixture.stop().await;
}

/// A stream given an idle timeout of the broker's settle budget, its server silent for four idle
/// timeouts after the first item, ends with `Timeout` once the idle timeout has passed and before
/// the silence ends.
pub async fn idle_timeout_ends_a_silent_stream<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    if !streams(&fixture.capabilities()) {
        refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
        return fixture.stop().await;
    }
    let idle = idle_of(fixture.broker.budget());
    let silence_for = silence_of(fixture.broker.budget());
    let silence = silence_for.as_millis() as u64;
    let mut replies = fixture.rpc().stream::<_, u64>(PAUSE, &silence).idle_timeout(Bound::After(idle)).await.expect("the stream opens");
    let first = within::<B, _>(Duration::from_secs(10), "the first item", replies.next()).await.expect("the stream yields");
    assert_eq!(first.expect("the first item arrives"), 0);
    let silent = Instant::now();
    let ended = within::<B, _>(Duration::from_secs(10), "the idle timeout", replies.next()).await.expect("the stream yields its end");
    let waited = silent.elapsed();
    failed(ended, ErrorKind::Timeout);
    assert!(waited >= idle - Duration::from_millis(50), "the stream ended {waited:?} into the silence, before its idle timeout");
    assert!(waited < silence_for, "the stream ended {waited:?} into the silence, not at its {idle:?} idle timeout");
    assert!(replies.next().await.is_none(), "the stream yielded after its idle timeout");
    fixture.stop().await;
}

/// A stream given a deadline carries it as `deadline-ms`, and the server ends the stream there.
/// The deadline is the broker's settle budget and a fifth, 600 ms by default, so a tick crosses
/// the broker within it. The stream goes through a client link that never sends a `cancel`, so the
/// `cancel` the client sends when its own deadline passes does not reach the server.
pub async fn stream_deadline_is_the_server_s<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    if !streams(&fixture.capabilities()) {
        refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
        return fixture.stop().await;
    }
    let settle = fixture.broker.budget().settle;
    let deadline = settle + settle / 5;
    let link = MutedCancel(fixture.broker.client_link(&addresses(&[&fixture.server])));
    let client = client_over::<B, _>(link).await;
    let started = Instant::now();
    let mut ticks = client.rpc.stream::<_, u64>(TICKS, &()).deadline(deadline).await.expect("the stream opens");
    let mut arrived = 0;
    let ended = loop {
        match within::<B, _>(Duration::from_secs(10), "the stream's deadline", ticks.next()).await {
            Some(Ok(_)) => arrived += 1,
            Some(Err(error)) => break error,
            None => panic!("the stream ended cleanly {:?} after it opened, its deadline {deadline:?}", started.elapsed()),
        }
    };
    assert_eq!(ended.kind(), ErrorKind::Timeout, "what ended the stream: {ended:?}");
    assert!(arrived > 0, "no tick arrived before the stream's deadline");
    drop(ticks);
    let probe = fixture.server.probe.clone();
    assert!(
        eventually::<B>(deadline + settle, || probe.stopped()).await,
        "the ticking stream was still running {:?} after a stream with a {deadline:?} deadline opened",
        started.elapsed()
    );
    assert_eq!(probe.cancelled(), Some(Some(CancelReason::Deadline)), "what ended the ticking stream");
    client.close().await;
    fixture.stop().await;
}

/// A stream given neither an idle timeout nor a deadline is bounded by neither, the client's
/// timeout included: on a client whose timeout is half the broker's settle budget, a stream silent
/// for four settle budgets between its two items yields both and ends cleanly.
pub async fn stream_with_neither_bound_runs_on<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    if !streams(&fixture.capabilities()) {
        refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
        return fixture.stop().await;
    }
    let budget = fixture.broker.budget();
    let client = fixture.rpc().clone().timeout(Bound::After(idle_of(budget) / 2)).expect("a nonzero timeout");
    let started = Instant::now();
    let silence_for = silence_of(budget);
    let silence = silence_for.as_millis() as u64;
    let replies = client.stream::<_, u64>(PAUSE, &silence).await.expect("the stream opens");
    let items: Vec<_> = within::<B, _>(silence_for + Duration::from_secs(10), "the paused stream", replies.collect()).await;
    let items: Vec<u64> = items
        .into_iter()
        .map(|item| item.unwrap_or_else(|error| panic!("the stream failed {:?} after it opened: {error:?}", started.elapsed())))
        .collect();
    assert_eq!(items, vec![0, 1], "the paused stream's items");
    assert!(started.elapsed() >= silence_for, "the stream ended {:?} after it opened, before its silence", started.elapsed());
    fixture.stop().await;
}

/// The fixture's client with every stream's idle timeout set to `idle`.
fn idle_client<B: Broker>(fixture: &Fixture<B>, idle: Duration) -> RpcClient {
    fixture.rpc().clone().idle_timeout(Bound::After(idle)).expect("a nonzero idle timeout")
}

/// Opens a stream on [`PAUSE`] silent for `silence` between its two items, its idle timeout
/// `idle` on the call.
async fn paused<B: Broker>(client: &RpcClient, silence: Duration, idle: Bound) -> RpcStream<u64> {
    let millis = silence.as_millis() as u64;
    let opened = client.stream::<_, u64>(PAUSE, &millis).idle_timeout(idle);
    within::<B, _>(Duration::from_secs(10), "the stream's opening", opened.into_future()).await.expect("the stream opens")
}

/// Reads a stream on [`PAUSE`] to its end: both items, and an end no sooner than the silence
/// between them.
async fn runs_through_the_silence<B: Broker>(replies: RpcStream<u64>, silence: Duration, what: &str) {
    let started = Instant::now();
    let items: Vec<_> = within::<B, _>(silence + Duration::from_secs(10), "the paused stream", replies.collect()).await;
    let items: Vec<u64> = items
        .into_iter()
        .map(|item| item.unwrap_or_else(|error| panic!("{what}: the stream failed {:?} after it opened: {error:?}", started.elapsed())))
        .collect();
    assert_eq!(items, vec![0, 1], "{what}: the paused stream's items");
    assert!(started.elapsed() >= silence, "{what}: the stream ended {:?} after it opened, before its silence", started.elapsed());
}

/// Reads a stream on [`PAUSE`] past its first item into the silence, which must end it with
/// `Timeout` at `idle`, not before and not once the silence is over.
async fn ends_at<B: Broker>(mut replies: RpcStream<u64>, idle: Duration, silence: Duration, what: &str) {
    let first = within::<B, _>(Duration::from_secs(10), "the first item", replies.next()).await.expect("the stream yields");
    assert_eq!(first.expect("the first item arrives"), 0, "{what}: the first item");
    let silent = Instant::now();
    let ended = within::<B, _>(silence + Duration::from_secs(10), "the idle timeout", replies.next()).await.expect("the stream yields its end");
    let waited = silent.elapsed();
    failed(ended, ErrorKind::Timeout);
    assert!(waited >= idle - Duration::from_millis(50), "{what}: the stream ended {waited:?} into the silence, before its {idle:?} idle timeout");
    assert!(waited < silence, "{what}: the stream ended {waited:?} into the silence, not at its {idle:?} idle timeout");
}

/// On a client whose idle timeout is the broker's settle budget, a stream given
/// `Bound::Unbounded` on the call has none: silent for four settle budgets between its items, it
/// yields both and ends cleanly.
pub async fn unbounded_idle_timeout_outlasts_the_client_s<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    if !streams(&fixture.capabilities()) {
        refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
        return fixture.stop().await;
    }
    let budget = fixture.broker.budget();
    let client = idle_client(&fixture, idle_of(budget));
    let replies = paused::<B>(&client, silence_of(budget), Bound::Unbounded).await;
    runs_through_the_silence::<B>(replies, silence_of(budget), "a stream at `Bound::Unbounded`").await;
    fixture.stop().await;
}

/// On a client whose idle timeout is the broker's settle budget, a stream given `Bound::Default`
/// on the call takes the client's: silent for four settle budgets after its first item, it ends
/// with `Timeout` at the client's idle timeout.
pub async fn default_idle_timeout_is_the_client_s<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    if !streams(&fixture.capabilities()) {
        refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
        return fixture.stop().await;
    }
    let budget = fixture.broker.budget();
    let client = idle_client(&fixture, idle_of(budget));
    let replies = paused::<B>(&client, silence_of(budget), Bound::Default).await;
    ends_at::<B>(replies, idle_of(budget), silence_of(budget), "a stream at `Bound::Default`").await;
    fixture.stop().await;
}

/// On a client whose idle timeout outlasts the silence, eight settle budgets, a stream given the
/// settle budget on the call ends with `Timeout` there, four settle budgets before its second
/// item, which the client's idle timeout alone would let through.
pub async fn shorter_idle_timeout_replaces_the_client_s<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    if !streams(&fixture.capabilities()) {
        refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
        return fixture.stop().await;
    }
    let budget = fixture.broker.budget();
    let client = idle_client(&fixture, silence_of(budget) * 2);
    let replies = paused::<B>(&client, silence_of(budget), Bound::After(idle_of(budget))).await;
    ends_at::<B>(replies, idle_of(budget), silence_of(budget), "a stream given a shorter idle timeout").await;
    fixture.stop().await;
}

/// A stream given an idle timeout of zero on the call fails when it is awaited, `BadRequest` with
/// the reason `zero_timeout` and a `ZeroTimeout` as its source, before its client connects or
/// sends a frame. A unary call through the same link afterwards shows the counts move.
pub async fn zero_idle_timeout_is_refused_before_any_frame<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    let counts = Arc::new(Counts::default());
    let link = Counted { link: fixture.broker.client_link(&addresses(&[&fixture.server])), counts: Arc::clone(&counts) };
    let client = client_over::<B, _>(link).await;
    let refused = within::<B, _>(
        Duration::from_secs(10),
        "the refusal",
        client.rpc.stream::<_, u64>(PAUSE, &0u64).idle_timeout(Bound::After(Duration::ZERO)).into_future(),
    )
    .await;
    let refused = failed(refused.map(drop), ErrorKind::BadRequest);
    assert_eq!(refused.reason(), Some("zero_timeout"), "the refusal's reason: {refused:?}");
    assert!(
        refused.source().is_some_and(|source| source.downcast_ref::<ZeroTimeout>().is_some()),
        "the refusal's source is not a `ZeroTimeout`: {refused:?}"
    );
    assert_eq!(
        (counts.connects.load(Ordering::SeqCst), counts.frames.load(Ordering::SeqCst)),
        (0, 0),
        "the client's connects and frames sent before the refusal"
    );
    let sum = client.rpc.request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).timeout(Duration::from_secs(10)).await;
    assert_eq!(sum.expect("a unary call after the refusal is answered"), Sum { sum: 5 });
    assert!(
        counts.connects.load(Ordering::SeqCst) > 0 && counts.frames.load(Ordering::SeqCst) > 0,
        "the counts did not move for a call that reached the server"
    );
    client.close().await;
    fixture.stop().await;
}

/// On a client whose idle timeout is the broker's settle budget, a stream given
/// `Bound::After(Duration::MAX)` on the call, an end no `Instant` holds, neither panics nor ends
/// at the client's idle timeout: silent for four settle budgets, it yields both items and ends
/// cleanly.
pub async fn longest_idle_timeout_does_not_panic<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    if !streams(&fixture.capabilities()) {
        refused_at_startup(&fixture.broker, Mounts { streaming: true, binary: false, every_instance: false }).await;
        return fixture.stop().await;
    }
    let budget = fixture.broker.budget();
    let client = idle_client(&fixture, idle_of(budget));
    let replies = paused::<B>(&client, silence_of(budget), Bound::After(Duration::MAX)).await;
    runs_through_the_silence::<B>(replies, silence_of(budget), "a stream at `Bound::After(Duration::MAX)`").await;
    fixture.stop().await;
}

/// The header each call in the zero-bound scenarios below carries, which the server's [`Tapped`]
/// link records for every opening frame it delivers.
pub(crate) const MARK: &str = "x-conformance-mark";

/// How many zero-bound calls each scenario below makes. A zero that is not refused times the call
/// out at once, and whether its `req` is sent first is a race the client's `select!` decides at
/// random, so one call that reaches no server would not show the refusal; eight leave a chance
/// of 1 in 256 that a client sending at random sends none of them.
const ZERO_CALLS: usize = 8;

/// Asserts `refused` is a zero bound's refusal: `BadRequest`, the reason `zero_timeout`, a
/// `ZeroTimeout` as its source.
fn zero_refused<T: std::fmt::Debug>(refused: Result<T, RpcError>, what: &str) {
    let refused = failed(refused, ErrorKind::BadRequest);
    assert_eq!(refused.reason(), Some("zero_timeout"), "{what}: the refusal's reason: {refused:?}");
    assert!(
        refused.source().is_some_and(|source| source.downcast_ref::<ZeroTimeout>().is_some()),
        "{what}: the refusal's source is not a `ZeroTimeout`: {refused:?}"
    );
}

/// F392: a call given `.timeout(Duration::ZERO)` fails when it is awaited, `BadRequest` with the
/// reason `zero_timeout` and a `ZeroTimeout` as its source, and its server sees no request: the
/// server's own link records the marked opening frames it delivers, and after eight refused calls
/// and a ninth with a ten-second timeout, answered, it has delivered the ninth alone. Every call
/// names one pattern over one connection, so a refused call's frame, had it been sent, would
/// have reached the server before the ninth's.
pub async fn zero_call_timeout_is_refused_before_the_server_sees_it<B: Broker>() {
    let tap = Tap::default();
    let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
    for _ in 0..ZERO_CALLS {
        let call = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "zero").timeout(Duration::ZERO);
        zero_refused(within::<B, _>(Duration::from_secs(10), "the refusal", call.into_future()).await, "`Call::timeout(Duration::ZERO)`");
    }
    let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
    assert_eq!(sum.expect("a call with a ten-second timeout is answered"), Sum { sum: 5 });
    assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received");
    fixture.stop().await;
}

/// F392: a stream given `.deadline(Duration::ZERO)` fails when it is awaited, `BadRequest` with
/// the reason `zero_timeout` and a `ZeroTimeout` as its source, and its server sees no request,
/// as in [`zero_call_timeout_is_refused_before_the_server_sees_it`]: the ninth stream, given a
/// ten-second deadline, is answered its two items on a link carrying streamed replies, and the
/// server has delivered it alone. On UDP, which carries none, the ninth stream is refused
/// `shape_unsupported` before any I/O, and a marked request after it is the one call the server
/// delivers.
pub async fn zero_stream_deadline_is_refused_before_the_server_sees_it<B: Broker>() {
    let tap = Tap::default();
    let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
    for _ in 0..ZERO_CALLS {
        let call = fixture.rpc().stream::<_, u32>(COUNT, &2u32).header(MARK, "zero").deadline(Duration::ZERO);
        let refused = within::<B, _>(Duration::from_secs(10), "the refusal", call.into_future()).await;
        zero_refused(refused.map(drop), "`StreamCall::deadline(Duration::ZERO)`");
    }
    let call = fixture.rpc().stream::<_, u32>(COUNT, &2u32).header(MARK, "after").deadline(Duration::from_secs(10));
    let opened = within::<B, _>(Duration::from_secs(10), "the stream's opening", call.into_future()).await;
    if streams(&fixture.capabilities()) {
        let replies = opened.expect("the stream opens");
        let items: Vec<_> = within::<B, _>(Duration::from_secs(10), "the stream", replies.collect()).await;
        let items: Vec<u32> = items.into_iter().map(|item| item.expect("the stream yields")).collect();
        assert_eq!(items, vec![1, 2], "the stream given a ten-second deadline");
    } else {
        match opened.err() {
            Some(error) if error.reason() == Some("shape_unsupported") => {}
            other => panic!("a stream on a link carrying none was not refused `shape_unsupported`: {other:?}"),
        }
        let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
        assert_eq!(sum.expect("a request after the refused stream is answered"), Sum { sum: 5 });
    }
    assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received");
    fixture.stop().await;
}

/// A call made `.within` an execution whose deadline has passed fails `Timeout` when it is
/// awaited, before it connects, and its server sees nothing. Two executions, each with a deadline
/// of now: a standalone one, which the app cancels at its deadline, and one opened as a transport
/// opens one, which nothing cancels, so its deadline alone refuses the calls. Inside each, a
/// request, a stream and an event, eight of each, each refused; then a request outside both,
/// answered, and the server has delivered that request alone. The event's frame names another
/// pattern, so a settle budget after the answer passes before the server's link is read.
pub async fn passed_deadline_is_refused_before_the_server_sees_it<B: Broker>() {
    let tap = Tap::default();
    let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
    let passed = crate::rt::runtime::<B>().now();
    let mut outcomes =
        fixture.client.execute(ExecOptions::new().deadline(passed), async |exec| past_deadline::<B>(&fixture, &exec.handle()).await).await;
    let opened = fixture.client.open(ExecOptions::new().deadline(passed));
    outcomes.extend(past_deadline::<B>(&fixture, &opened.handle()).await);
    assert!(!opened.is_cancelled(), "the opened execution was cancelled, so its deadline alone did not refuse the calls");
    drop(opened);
    let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
    assert_eq!(sum.expect("a call outside the execution is answered"), Sum { sum: 5 });
    crate::rt::sleep::<B>(fixture.broker.budget().settle).await;
    assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received; the calls' outcomes: {outcomes:?}");
    assert_eq!(fixture.server.probe.events(), 0, "an event sent past its execution's deadline reached its handler");
    for (what, outcome) in outcomes {
        match outcome {
            Err(error) if error.kind() == ErrorKind::Timeout => {}
            other => panic!("{what} made inside an execution whose deadline has passed: expected `Timeout`, got: {other:?}"),
        }
    }
    fixture.stop().await;
}

/// A request, a stream and an event made `.within` `exec`, eight of each, and how each ended.
async fn past_deadline<B: Broker>(fixture: &Fixture<B>, exec: &ExecutionRef) -> Vec<(&'static str, Result<(), RpcError>)> {
    let mut outcomes = Vec::new();
    for _ in 0..ZERO_CALLS {
        let call = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "passed").within(exec);
        outcomes.push(("a request", within::<B, _>(Duration::from_secs(10), "the request", call.into_future()).await.map(drop)));
        let stream = fixture.rpc().stream::<_, u32>(COUNT, &2u32).header(MARK, "passed").within(exec);
        outcomes.push(("a stream", within::<B, _>(Duration::from_secs(10), "the stream", stream.into_future()).await.map(drop)));
        let event = fixture.rpc().emit(EVENT, &1u32).header(MARK, "passed").within(exec);
        outcomes.push(("an event", within::<B, _>(Duration::from_secs(10), "the event", event.into_future()).await));
    }
    outcomes
}

/// A call made `.within` an execution already cancelled fails `Unavailable` when it is awaited,
/// before it connects, and its server sees nothing: a request and a stream, eight of each, each
/// refused, then a request outside the execution, answered, and the server has delivered that
/// request alone.
pub async fn cancelled_execution_s_call_is_refused_before_the_server_sees_it<B: Broker>() {
    let tap = Tap::default();
    let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
    let outcomes = fixture
        .client
        .execute(ExecOptions::new(), async |exec| {
            exec.cancel();
            let exec = exec.handle();
            let mut outcomes = Vec::new();
            for _ in 0..ZERO_CALLS {
                let call = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "cancelled").within(&exec);
                outcomes.push(("a request", within::<B, _>(Duration::from_secs(10), "the request", call.into_future()).await.map(drop)));
                let stream = fixture.rpc().stream::<_, u32>(COUNT, &2u32).header(MARK, "cancelled").within(&exec);
                outcomes.push(("a stream", within::<B, _>(Duration::from_secs(10), "the stream", stream.into_future()).await.map(drop)));
            }
            outcomes
        })
        .await;
    let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
    assert_eq!(sum.expect("a call outside the execution is answered"), Sum { sum: 5 });
    assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received; the calls' outcomes: {outcomes:?}");
    for (what, outcome) in outcomes {
        match outcome {
            Err(error) if error.kind() == ErrorKind::Unavailable => {}
            other => panic!("{what} made inside a cancelled execution: expected `Unavailable`, got: {other:?}"),
        }
    }
    fixture.stop().await;
}

/// The unit `deadline-ms` is written in, the most its truncation and its one-millisecond floor
/// move a deadline.
const DEADLINE_UNIT: Duration = Duration::from_millis(1);

/// F410: a call's `deadline-ms` is what is left of its caller's deadline when its frame is handed
/// to a connection already made, so the server's deadline is no later than the caller's, within
/// one unit, past the time the frame takes to reach it. A request, a stream and a streamed
/// request are made at once `.within` an execution, the first calls on a client whose link holds
/// each new connection for half the broker's settle budget before making it, the request and the
/// streamed request given a timeout longer than the execution has left, so the execution's
/// deadline is each call's own; the server's
/// handlers record the deadline they were given and the `deadline-ms` it came from, and the link
/// records when it was handed each call's frame. The frame's transit, from that handoff to the
/// server's reading of the header, is measured on the one clock the scenario's client and server
/// share: no value written before the frame is sent can account for it.
pub async fn measured_once_connected<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    let budget = fixture.broker.budget();
    let held = budget.settle / 2;
    let link = SlowConnect::new(fixture.broker.client_link(&addresses(&[&fixture.server])), Hold::Waits(held));
    let handoffs = link.handoffs.clone();
    let client = client_over::<B, _>(link).await;
    let left = held + budget.boot;
    let deadline = crate::rt::runtime::<B>().now() + left;
    let opened = client.open(ExecOptions::new().deadline(deadline));
    let exec = opened.handle();
    let streaming = streams(&fixture.capabilities());
    let request = async {
        let call = client.rpc.request::<_, ()>(DEADLINE, &()).header(MARK, "request").timeout(left * 2).within(&exec);
        ("request", call.await)
    };
    let stream = async {
        let call = client.rpc.stream::<_, u32>(DEADLINE_STREAM, &()).header(MARK, "stream").within(&exec);
        let outcome = match call.await {
            Ok(replies) => replies.collect::<Vec<_>>().await.into_iter().collect::<Result<Vec<u32>, _>>().map(|items| assert_eq!(items, vec![1])),
            Err(error) => Err(error),
        };
        ("stream", outcome)
    };
    let streamed = async {
        let items = futures_util::stream::iter([1i64, 2]);
        let call = client.rpc.send_stream::<_, i64>(DEADLINE_SUM, items).header(MARK, "streamed").timeout(left * 2).within(&exec);
        ("streamed", call.await.map(|sum| assert_eq!(sum, 3)))
    };
    let calls = async {
        if streaming {
            let (request, stream, streamed) = futures_util::join!(request, stream, streamed);
            vec![request, stream, streamed]
        } else {
            vec![request.await]
        }
    };
    let outcomes = within::<B, _>(left + budget.settle, "the calls", calls).await;
    // A handle to an execution still open holds the client's app at its close.
    drop(exec);
    drop(opened);
    for (mark, outcome) in &outcomes {
        if let Err(error) = outcome {
            panic!("the {mark} made on a new connection failed: {error:?}");
        }
    }
    let seen = fixture.server.probe.seen();
    let handed = handoffs.all();
    let mut report = Vec::new();
    let mut late = false;
    for (mark, _) in &outcomes {
        let taken = seen.iter().find(|seen| seen.mark.as_deref() == Some(*mark)).unwrap_or_else(|| panic!("the server took no {mark}: {seen:?}"));
        let server = taken.deadline.unwrap_or_else(|| panic!("the server gave the {mark} no deadline: {taken:?}"));
        let millis: u64 = taken.header.as_deref().and_then(|value| value.parse().ok()).unwrap_or_else(|| panic!("the {mark} carried no readable `deadline-ms`: {taken:?}"));
        let read = server - Duration::from_millis(millis);
        let sent = handed.iter().find(|(handed, _)| handed == mark).map(|(_, at)| *at).unwrap_or_else(|| panic!("the link was handed no {mark}: {handed:?}"));
        let transit = read.saturating_duration_since(sent);
        late |= server > deadline + transit + DEADLINE_UNIT;
        report.push(format!(
            "the {mark}: `deadline-ms: {millis}`, the server's deadline {:+.3} ms from the caller's, its frame {:.3} ms in transit",
            signed_millis(server, deadline),
            transit.as_secs_f64() * 1e3
        ));
    }
    assert!(!late, "a server's deadline was later than its caller's by more than the frame's transit and one unit, its connect held {held:?}:\n{}", report.join("\n"));
    client.close().await;
    fixture.stop().await;
}

/// F410: a call whose connect outlasts its caller's deadline fails `Timeout` once the connect
/// returns, and its server sees nothing. For each shape the link carries, a request, a stream, a
/// streamed request and an event, a client whose link holds its connect twice as long as the
/// execution the call is made `.within` has left, a fifth of the broker's settle budget: once
/// with a connect that waits, which the call's own timer cuts short, and once with one that makes
/// its connection and then blocks its thread, so the connect returns in the poll that finds the
/// deadline passed, before the call's timer can be polled again. Then a
/// request on a connection already made, answered, and the server has delivered that request
/// alone, no event handled.
///
/// Only the blocking half is evidence that a frame is stamped and refused once the connection is
/// in hand. The waiting half pins behaviour that predates that check: the call's timer ends a
/// connect that waits at the deadline, so it passed against the client before the check existed.
/// The block follows the connection rather than preceding it: a block ahead of a connect that still
/// awaits ends in a poll that returns pending, and the call's timer, armed for what is left of the
/// bound, answers at the next poll whether or not the check exists.
pub async fn connect_past_the_deadline_is_refused_before_the_server_sees_it<B: Broker>() {
    let tap = Tap::default();
    let fixture = Fixture::<B>::start_over(Count::Default, |broker| Tapped { link: broker.link(), tap: tap.clone() }).await;
    let budget = fixture.broker.budget();
    let left = budget.settle / 5;
    let held = left * 2;
    let streaming = streams(&fixture.capabilities());
    let mut outcomes = Vec::new();
    // `Hold::Waits` is the pin, `Hold::BlocksConnected` the evidence; see the doc above.
    for hold in [Hold::Waits(held), Hold::BlocksConnected(held)] {
        for shape in ["a request", "a stream", "a streamed request", "an event"] {
            if !streaming && matches!(shape, "a stream" | "a streamed request") {
                continue;
            }
            let link = SlowConnect::new(fixture.broker.client_link(&addresses(&[&fixture.server])), hold);
            let client = client_over::<B, _>(link).await;
            let opened = client.open(ExecOptions::new().deadline(crate::rt::runtime::<B>().now() + left));
            let exec = opened.handle();
            let call = async {
                match shape {
                    "a request" => client.rpc.request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "slow").within(&exec).await.map(drop),
                    "a stream" => client.rpc.stream::<_, u32>(COUNT, &2u32).header(MARK, "slow").within(&exec).await.map(drop),
                    "a streamed request" => {
                        let items = futures_util::stream::iter([1i64, 2]);
                        client.rpc.send_stream::<_, i64>(SUM, items).header(MARK, "slow").within(&exec).await.map(drop)
                    }
                    _ => client.rpc.emit(EVENT, &1u32).header(MARK, "slow").within(&exec).await,
                }
            };
            let outcome = within::<B, _>(held + budget.boot, "the call", call).await;
            outcomes.push((hold, shape, outcome));
            // A handle to an execution still open holds the client's app at its close.
            drop(exec);
            drop(opened);
            client.close().await;
        }
    }
    let sum = fixture.rpc().request::<_, Sum>(ADD, &Add { a: 2, b: 3 }).header(MARK, "after").timeout(Duration::from_secs(10)).await;
    assert_eq!(sum.expect("a call on a connection already made is answered"), Sum { sum: 5 });
    crate::rt::sleep::<B>(budget.settle).await;
    assert_eq!(tap.marks(), vec!["after"], "the marked calls the server received; the calls' outcomes: {outcomes:?}");
    assert_eq!(fixture.server.probe.events(), 0, "an event whose connect outlasted its deadline reached its handler: {outcomes:?}");
    for (hold, shape, outcome) in outcomes {
        match outcome {
            Err(error) if error.kind() == ErrorKind::Timeout => {}
            other => panic!("{shape} whose connect {hold:?} past its deadline: expected `Timeout`, got: {other:?}"),
        }
    }
    fixture.stop().await;
}

/// How many calls [`blocked_connect_s_timer_ends_with_its_bound`] makes. A timer that an order
/// picked at random arms after the work's first poll is late in half the calls; sixteen leave a
/// chance of one in 65,536 that it is never seen.
const BLOCKED_CALLS: usize = 16;

/// The `deadline-ms` [`blocked_connect_s_timer_ends_with_its_bound`]'s server is given, ten
/// seconds, past every bound the scenario sets: the client's `cancel` stops the handler.
const UNANSWERED: &str = "10000";

/// F411: a call's timer is armed for the end of the call's bound, whatever blocked the call's
/// first poll. Sixteen requests, each the first call of a fresh client whose link blocks its
/// thread in the connect for half the call's timeout, two fifths of the broker's settle budget, to
/// a handler that stalls. A [`Stamped`] link below the client writes the server a ten-second
/// deadline, `UNANSWERED`, so the server's own `timeout` does not answer the call at its bound and
/// only the client's timer can. Each fails `Timeout`.
///
/// Each client's app is timed by an `ArmedClock` of its own over the runtime's clock, which
/// records the instant each sleep ends, read where a clock that arms a sleep at its first poll
/// arms it, and the instant a sleep that ran to its end ended. A call passes when a sleep its
/// client asked for after the call began ends no earlier than the call's start plus its timeout
/// and no later than the connect's start plus the timeout, and ran to its end before the call
/// answered: the timer that ended the call was armed for the bound counted from the call. A timer
/// armed after the block for a full timeout ends half a timeout beyond that window; a call
/// answered `Timeout` before any such sleep ended was not ended by its timer. A call whose
/// connect returned past the bound is answered by the refusal at the write, whatever the timer
/// does, and passes on `Timeout` alone. The window follows from the order of the clock's reads on
/// one thread, so load moves no threshold; the wall-clock time a call takes to answer is not
/// asserted. A clock per client keeps a sleep an earlier client's lingering connection asks for,
/// `CUT_GRACE` on TCP, out of the calls that follow it.
///
/// The report on a failure gives, for each call, its sleeps, its connects and its answer against
/// the call's start, on the runtime's clock and the std clock.
pub async fn blocked_connect_s_timer_ends_with_its_bound<B: Broker>() {
    let fixture = Fixture::<B>::start().await;
    let budget = fixture.broker.budget();
    let timeout = budget.settle * 2 / 5;
    let blocked = timeout / 2;
    let mut calls = Vec::new();
    for _ in 0..BLOCKED_CALLS {
        let clock = ArmedClock::new(crate::rt::runtime::<B>());
        let stamped = Stamped { link: fixture.broker.client_link(&addresses(&[&fixture.server])), value: UNANSWERED };
        let link = SlowConnect::new(stamped, Hold::Blocks(blocked));
        let connects = link.connects.clone();
        let client = client_timed::<B, _>(link, clock.clone()).await;
        clock.take();
        let started = Instants::now(&*clock.clock);
        let call = client.rpc.request::<_, ()>(STALL, &()).timeout(timeout).into_future();
        let outcome = within::<B, _>(timeout + blocked + budget.boot, "the call", call).await;
        let answered = Instants::now(&*clock.clock);
        calls.push(Blocked { started, answered, connects: connects.all(), sleeps: clock.take(), outcome });
        client.close().await;
    }
    if !calls.iter().all(|call| call.armed_within(timeout)) {
        let report: Vec<String> = calls.iter().map(Blocked::report).collect();
        panic!(
            "a call given {timeout:?} over a connect blocking {blocked:?} failed other than `Timeout`, or, its connect returning \
             inside its bound, no sleep it asked for ended inside [the call's start + {timeout:?}, the connect's start + \
             {timeout:?}] on the runtime's clock before it answered; every call:\n{}",
            report.join("\n")
        );
    }
    fixture.stop().await;
}

/// A clock that records, for each sleep asked of it, when it was asked for, the instant it ends,
/// read at its first poll: where a clock that arms a sleep on its first poll arms it, the latest
/// instant a sleep's timer can be armed, and when it ended, read as it ends.
#[derive(Clone)]
struct ArmedClock {
    clock: Arc<dyn Runtime>,
    sleeps: Arc<Mutex<Vec<Armed>>>,
}

/// One sleep an [`ArmedClock`] recorded, on its clock: when it was asked for, when it ends,
/// `None` for an end past the clock's range, and when it ended, unset for one that has not or that
/// the clock refused.
#[derive(Clone, Debug)]
struct Armed {
    asked: Instant,
    ends: Option<Instant>,
    ended: Arc<OnceLock<Instant>>,
}

impl ArmedClock {
    fn new(clock: Arc<dyn Runtime>) -> ArmedClock {
        ArmedClock { clock, sleeps: Arc::default() }
    }

    /// The sleeps recorded since the last call, cleared.
    fn take(&self) -> Vec<Armed> {
        std::mem::take(&mut *self.sleeps.lock().unwrap_or_else(PoisonError::into_inner))
    }
}

impl Timer for ArmedClock {
    fn sleep(&self, d: Duration) -> ulo::BoxFuture<'static, ()> {
        let slept = self.try_sleep(d);
        Box::pin(async move {
            let _ = slept.await;
        })
    }

    fn now(&self) -> Instant {
        self.clock.now()
    }

    fn try_sleep(&self, d: Duration) -> ulo::BoxFuture<'static, Result<(), ulo::Refused>> {
        let asked = self.clock.now();
        let (clock, sleeps) = (Arc::clone(&self.clock), Arc::clone(&self.sleeps));
        Box::pin(async move {
            let ends = clock.now().checked_add(d);
            let ended = Arc::new(OnceLock::new());
            sleeps.lock().unwrap_or_else(PoisonError::into_inner).push(Armed { asked, ends, ended: Arc::clone(&ended) });
            let slept = clock.try_sleep(d).await;
            if slept.is_ok() {
                let _ = ended.set(clock.now());
            }
            slept
        })
    }
}

/// One call of [`blocked_connect_s_timer_ends_with_its_bound`]: when it was made and answered,
/// when its client's connects began and returned, the sleeps its client's clock armed, and its
/// outcome.
struct Blocked {
    started: Instants,
    answered: Instants,
    connects: Vec<(Instants, Instants)>,
    sleeps: Vec<Armed>,
    outcome: Result<(), RpcError>,
}

impl Blocked {
    /// Whether the call failed `Timeout` and its timer was armed in time.
    fn armed_within(&self, timeout: Duration) -> bool {
        matches!(&self.outcome, Err(error) if error.kind() == ErrorKind::Timeout) && self.timer_armed_in_time(timeout)
    }

    /// Whether the first connect returned past `started + timeout` or a sleep its client asked
    /// for after `started` ends within `[started + timeout, connect + timeout]` and ended before
    /// the call answered, on the runtime's clock. A call that began no connect, one taking a
    /// connection another call opened, has no upper end to hold the sleep to.
    fn timer_armed_in_time(&self, timeout: Duration) -> bool {
        let earliest = self.started.timer + timeout;
        let latest = self.connects.first().map(|(connect, _)| connect.timer + timeout);
        let ended_it = |sleep: &Armed| {
            sleep.asked >= self.started.timer
                && sleep.ends.is_some_and(|ends| ends >= earliest && latest.is_none_or(|latest| ends <= latest))
                && sleep.ended.get().is_some_and(|ended| *ended <= self.answered.timer)
        };
        let connected_past_the_bound = self.connects.first().is_some_and(|(_, returned)| returned.timer >= earliest);
        connected_past_the_bound || self.sleeps.iter().any(ended_it)
    }

    fn report(&self) -> String {
        let since = |at: Instants| format!("{:+.1} ms by std, {:+.1} ms by the runtime", signed_millis(at.std, self.started.std), signed_millis(at.timer, self.started.timer));
        let on_runtime = |at: Instant| format!("{:+.3} ms", signed_millis(at, self.started.timer));
        let connects: Vec<String> = self
            .connects
            .iter()
            .map(|(began, returned)| format!("a connect began {} and returned {}", since(*began), since(*returned)))
            .collect();
        let sleeps: Vec<String> = self
            .sleeps
            .iter()
            .map(|sleep| {
                let ended = sleep.ended.get().map_or_else(|| "not ended".to_owned(), |ended| format!("ended {}", on_runtime(*ended)));
                match sleep.ends {
                    Some(ends) => format!("a sleep asked {} ending {}, {ended}", on_runtime(sleep.asked), on_runtime(ends)),
                    None => format!("a sleep asked {} ending past the clock's range, {ended}", on_runtime(sleep.asked)),
                }
            })
            .collect();
        format!(
            "answered {}; {}; {}; the runtime's clock read {:+.3} ms from std as the call was made; {:?}",
            since(self.answered),
            if connects.is_empty() { "no connect".to_owned() } else { connects.join(", ") },
            if sleeps.is_empty() { "no sleep".to_owned() } else { sleeps.join(", ") },
            signed_millis(self.started.timer, self.started.std),
            self.outcome
        )
    }
}

/// One moment on the std clock and on a runtime's, read back to back.
#[derive(Clone, Copy, Debug)]
struct Instants {
    std: Instant,
    timer: Instant,
}

impl Instants {
    fn now(timer: &dyn Timer) -> Instants {
        Instants { std: Instant::now(), timer: timer.now() }
    }
}

/// When each connect of a [`SlowConnect`] link began and returned, on the std clock and on the
/// clock of the runtime the client handed it.
#[derive(Clone, Default)]
struct Connects(Arc<Mutex<Vec<(Instants, Instants)>>>);

impl Connects {
    fn all(&self) -> Vec<(Instants, Instants)> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
    }
}

/// `a - b` in milliseconds, negative when `a` is the earlier.
fn signed_millis(a: Instant, b: Instant) -> f64 {
    match a.checked_duration_since(b) {
        Some(later) => later.as_secs_f64() * 1e3,
        None => -(b.duration_since(a).as_secs_f64() * 1e3),
    }
}

/// How a [`SlowConnect`] link holds each connect.
#[derive(Clone, Copy, Debug)]
enum Hold {
    /// Waits on the client's runtime before making the connection, as a connect waiting on its
    /// peer does.
    Waits(Duration),
    /// Blocks the thread polling the connect before making the connection, as a connect that does
    /// blocking work first does: the connect's first poll lasts the block.
    Blocks(Duration),
    /// Makes the connection, then blocks the thread polling the connect, as a connect finishing with
    /// blocking work does: the connect returns in the poll that ends the block, the call's next step
    /// with it.
    BlocksConnected(Duration),
}

/// When a [`SlowConnect`] link was handed each opening frame or event carrying [`MARK`], with the
/// mark, on the client's clock.
#[derive(Clone, Default)]
struct Handoffs(Arc<Mutex<Vec<(String, Instant)>>>);

impl Handoffs {
    fn all(&self) -> Vec<(String, Instant)> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
    }
}

/// A client link holding each connect for its [`Hold`] before making it, as a slow network or a
/// handshake does, and recording its [`Handoffs`] and [`Connects`].
struct SlowConnect<L> {
    link: L,
    hold: Hold,
    handoffs: Handoffs,
    connects: Connects,
}

impl<L> SlowConnect<L> {
    fn new(link: L, hold: Hold) -> Self {
        SlowConnect { link, hold, handoffs: Handoffs::default(), connects: Connects::default() }
    }
}

impl<L: Link> Link for SlowConnect<L> {
    const NAME: &'static str = L::NAME;

    fn capabilities(&self) -> Capabilities {
        self.link.capabilities()
    }

    fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.link.prepare(app)
    }

    fn usable(&self) -> Result<(), BoxError> {
        self.link.usable()
    }

    fn max_inflight(&mut self, calls: Count) {
        self.link.max_inflight(calls);
    }

    fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
        self.link.subscribable(subscriptions)
    }

    fn listen(&self, patterns: &[Subscription]) -> impl Future<Output = Result<Inbound, BoxError>> + Send {
        self.link.listen(patterns)
    }

    async fn connect(&self, runtime: &Arc<dyn Runtime>) -> Result<Outbound, BoxError> {
        let began = Instants::now(&**runtime);
        match self.hold {
            Hold::Waits(held) => runtime.sleep(held).await,
            Hold::Blocks(held) => std::thread::sleep(held),
            Hold::BlocksConnected(_) => {}
        }
        let connected = self.link.connect(runtime).await;
        if let (Ok(_), Hold::BlocksConnected(held)) = (&connected, self.hold) {
            std::thread::sleep(held);
        }
        self.connects.0.lock().unwrap_or_else(PoisonError::into_inner).push((began, Instants::now(&**runtime)));
        let Outbound { send, replies } = connected?;
        let (handoffs, clock) = (self.handoffs.clone(), Arc::clone(runtime));
        Ok(Outbound {
            send: Box::new(move |pattern, frame, reply_to| {
                let headers = match &frame {
                    Frame::Req { headers, .. } | Frame::Open { headers, .. } | Frame::Evt { headers, .. } => headers.get(MARK),
                    _ => None,
                };
                if let Some(mark) = headers {
                    handoffs.0.lock().unwrap_or_else(PoisonError::into_inner).push((mark.to_owned(), clock.now()));
                }
                send(pattern, frame, reply_to)
            }),
            replies,
        })
    }

    fn drain(&self) -> impl Future<Output = ()> + Send {
        self.link.drain()
    }

    fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.link.close()
    }

    fn bound(&self) -> Vec<BoundAddr> {
        self.link.bound()
    }
}

/// The value of [`MARK`] on each opening frame a [`Tapped`] link delivered, in arrival order, with
/// the frame's `deadline-ms`.
#[derive(Clone, Default)]
pub(crate) struct Tap(Arc<Mutex<Vec<Stamp>>>);

/// A delivered mark, and the `deadline-ms` its frame carried, `None` for none.
pub(crate) type Stamp = (String, Option<String>);

impl Tap {
    pub(crate) fn marks(&self) -> Vec<String> {
        self.stamps().into_iter().map(|(mark, _)| mark).collect()
    }

    pub(crate) fn stamps(&self) -> Vec<Stamp> {
        self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
    }
}

/// A server link recording, in its [`Tap`], every opening frame carrying [`MARK`] that it hands
/// the server, a `req`, an `open` or an `evt`, and the frame's `deadline-ms`.
pub(crate) struct Tapped<L> {
    pub(crate) link: L,
    pub(crate) tap: Tap,
}

impl<L: Link> Link for Tapped<L> {
    const NAME: &'static str = L::NAME;

    fn capabilities(&self) -> Capabilities {
        self.link.capabilities()
    }

    fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.link.prepare(app)
    }

    fn usable(&self) -> Result<(), BoxError> {
        self.link.usable()
    }

    fn max_inflight(&mut self, calls: Count) {
        self.link.max_inflight(calls);
    }

    fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
        self.link.subscribable(subscriptions)
    }

    async fn listen(&self, patterns: &[Subscription]) -> Result<Inbound, BoxError> {
        let inbound = self.link.listen(patterns).await?;
        let tap = self.tap.clone();
        Ok(Box::pin(inbound.inspect(move |delivery| {
            let headers = match &delivery.frame {
                Frame::Req { headers, .. } | Frame::Open { headers, .. } | Frame::Evt { headers, .. } => headers,
                _ => return,
            };
            if let Some(mark) = headers.get(MARK) {
                let deadline = headers.get("deadline-ms").map(str::to_owned);
                tap.0.lock().unwrap_or_else(PoisonError::into_inner).push((mark.to_owned(), deadline));
            }
        })))
    }

    fn connect(&self, runtime: &Arc<dyn Runtime>) -> impl Future<Output = Result<Outbound, BoxError>> + Send {
        self.link.connect(runtime)
    }

    fn drain(&self) -> impl Future<Output = ()> + Send {
        self.link.drain()
    }

    fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.link.close()
    }

    fn bound(&self) -> Vec<BoundAddr> {
        self.link.bound()
    }
}

/// How many times a [`Counted`] link connected and sent a frame.
#[derive(Default)]
struct Counts {
    connects: AtomicUsize,
    frames: AtomicUsize,
}

/// A client link counting its connects and the frames it sends.
struct Counted<L> {
    link: L,
    counts: Arc<Counts>,
}

impl<L: Link> Link for Counted<L> {
    const NAME: &'static str = L::NAME;

    fn capabilities(&self) -> Capabilities {
        self.link.capabilities()
    }

    fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.link.prepare(app)
    }

    fn usable(&self) -> Result<(), BoxError> {
        self.link.usable()
    }

    fn max_inflight(&mut self, calls: Count) {
        self.link.max_inflight(calls);
    }

    fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
        self.link.subscribable(subscriptions)
    }

    fn listen(&self, patterns: &[Subscription]) -> impl Future<Output = Result<Inbound, BoxError>> + Send {
        self.link.listen(patterns)
    }

    async fn connect(&self, runtime: &Arc<dyn Runtime>) -> Result<Outbound, BoxError> {
        self.counts.connects.fetch_add(1, Ordering::SeqCst);
        let Outbound { send, replies } = self.link.connect(runtime).await?;
        let counts = Arc::clone(&self.counts);
        Ok(Outbound {
            send: Box::new(move |pattern, frame, reply_to| {
                counts.frames.fetch_add(1, Ordering::SeqCst);
                send(pattern, frame, reply_to)
            }),
            replies,
        })
    }

    fn drain(&self) -> impl Future<Output = ()> + Send {
        self.link.drain()
    }

    fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.link.close()
    }

    fn bound(&self) -> Vec<BoundAddr> {
        self.link.bound()
    }
}

/// A client link that sends every frame but a `cancel`.
struct MutedCancel<L>(L);

impl<L: Link> Link for MutedCancel<L> {
    const NAME: &'static str = L::NAME;

    fn capabilities(&self) -> Capabilities {
        self.0.capabilities()
    }

    fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.0.prepare(app)
    }

    fn usable(&self) -> Result<(), BoxError> {
        self.0.usable()
    }

    fn max_inflight(&mut self, calls: Count) {
        self.0.max_inflight(calls);
    }

    fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
        self.0.subscribable(subscriptions)
    }

    fn listen(&self, patterns: &[Subscription]) -> impl Future<Output = Result<Inbound, BoxError>> + Send {
        self.0.listen(patterns)
    }

    async fn connect(&self, runtime: &Arc<dyn Runtime>) -> Result<Outbound, BoxError> {
        let Outbound { send, replies } = self.0.connect(runtime).await?;
        Ok(Outbound {
            send: Box::new(move |pattern, frame, reply_to| match frame {
                Frame::Cancel { .. } => Box::pin(async { Ok(()) }),
                frame => send(pattern, frame, reply_to),
            }),
            replies,
        })
    }

    fn drain(&self) -> impl Future<Output = ()> + Send {
        self.0.drain()
    }

    fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.0.close()
    }

    fn bound(&self) -> Vec<BoundAddr> {
        self.0.bound()
    }
}

/// A client link writing `deadline-ms: value` on every `req`, `open` and `evt` it sends, in place
/// of any the client stamped. The client refuses a `deadline-ms` its caller sets, so a value it
/// would not send, a deadline shorter than the client's own wait or one the server cannot read,
/// reaches a server only from below the client. Public for a link crate's own tests of the same.
pub struct Stamped<L> {
    pub link: L,
    pub value: &'static str,
}

impl<L: Link> Link for Stamped<L> {
    const NAME: &'static str = L::NAME;

    fn capabilities(&self) -> Capabilities {
        self.link.capabilities()
    }

    fn prepare(&mut self, app: &AppHandle) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.link.prepare(app)
    }

    fn usable(&self) -> Result<(), BoxError> {
        self.link.usable()
    }

    fn max_inflight(&mut self, calls: Count) {
        self.link.max_inflight(calls);
    }

    fn subscribable(&self, subscriptions: &[Subscription]) -> Result<(), BoxError> {
        self.link.subscribable(subscriptions)
    }

    fn listen(&self, patterns: &[Subscription]) -> impl Future<Output = Result<Inbound, BoxError>> + Send {
        self.link.listen(patterns)
    }

    async fn connect(&self, runtime: &Arc<dyn Runtime>) -> Result<Outbound, BoxError> {
        let Outbound { send, replies } = self.link.connect(runtime).await?;
        let value = self.value;
        Ok(Outbound {
            send: Box::new(move |on, frame, reply_to| {
                let frame = match frame {
                    Frame::Req { id, pattern, headers, data } => Frame::Req { id, pattern, headers: stamped(&headers, value), data },
                    Frame::Open { id, pattern, headers } => Frame::Open { id, pattern, headers: stamped(&headers, value) },
                    Frame::Evt { pattern, headers, data } => Frame::Evt { pattern, headers: stamped(&headers, value), data },
                    other => other,
                };
                send(on, frame, reply_to)
            }),
            replies,
        })
    }

    fn drain(&self) -> impl Future<Output = ()> + Send {
        self.link.drain()
    }

    fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
        self.link.close()
    }

    fn bound(&self) -> Vec<BoundAddr> {
        self.link.bound()
    }
}

/// `headers` with every `deadline-ms` replaced by one carrying `value`.
fn stamped(headers: &CallHeaders, value: &str) -> CallHeaders {
    let mut out = CallHeaders::new();
    for (name, kept) in headers.iter().filter(|(name, _)| *name != "deadline-ms") {
        out.insert(name, kept);
    }
    out.insert("deadline-ms", value);
    out
}

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

    fn at(base: Instant, millis: u64) -> Instants {
        let moment = base + Duration::from_millis(millis);
        Instants { std: moment, timer: moment }
    }

    fn sleep(base: Instant, asked: u64, ends: u64, ended: u64) -> Armed {
        Armed {
            asked: base + Duration::from_millis(asked),
            ends: Some(base + Duration::from_millis(ends)),
            ended: Arc::new(OnceLock::from(base + Duration::from_millis(ended))),
        }
    }

    fn call(base: Instant, connects: Vec<(Instants, Instants)>, sleeps: Vec<Armed>) -> Blocked {
        Blocked { started: at(base, 0), answered: at(base, 201), connects, sleeps, outcome: Ok(()) }
    }

    #[test]
    fn a_call_taking_a_connection_another_call_opened_is_held_to_its_own_timer() {
        let base = Instant::now();
        let timeout = Duration::from_millis(200);
        assert!(call(base, vec![], vec![sleep(base, 0, 200, 200)]).timer_armed_in_time(timeout));
        assert!(call(base, vec![], vec![sleep(base, 1, 201, 201)]).timer_armed_in_time(timeout), "no connect, no upper end");
        assert!(!call(base, vec![], vec![sleep(base, 0, 100, 100)]).timer_armed_in_time(timeout), "armed for too little");
        assert!(!call(base, vec![], vec![sleep(base, 0, 200, 250)]).timer_armed_in_time(timeout), "ended after the answer");
        assert!(!call(base, vec![], vec![]).timer_armed_in_time(timeout), "no sleep at all");
    }

    #[test]
    fn a_call_with_a_connect_holds_the_sleep_to_the_connects_start() {
        let base = Instant::now();
        let timeout = Duration::from_millis(200);
        let connect = vec![(at(base, 0), at(base, 100))];
        assert!(call(base, connect.clone(), vec![sleep(base, 0, 200, 200)]).timer_armed_in_time(timeout));
        assert!(!call(base, connect, vec![sleep(base, 100, 300, 200)]).timer_armed_in_time(timeout), "armed after the block");
    }
}