ostrya-remote 0.18.0

The push and pull protocol of ostrya: the wire codec, the push client session, and the ssh and HTTP transports
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
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
//! The client session of the pull against scripted servers over a bounded
//! in-process pipe. The tests cover the hello and the version, the pipeline,
//! the reply bodies, the length checks, the end of the session, and the errors
//! that later calls repeat. They also cover the open of a `PullSession` over
//! each transport, its request limit, and its read of the summary.

use std::collections::VecDeque;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use std::time::Duration;

use futures_io::{AsyncRead, AsyncWrite};
use futures_lite::future;
use futures_lite::io::AsyncReadExt;
use ostrya_core::RefSelector;
use ostrya_fetch::{FetcherOptions, Proxy};
use ostrya_remote::proto::{
    ErrorMessage, FrameReader, FrameWriter, GetReply, ListRefsRequest, MAX_REF_LISTING, Message,
    PULL_PROTOCOL_VERSION, PullHelloReply,
};
use ostrya_remote::transport::Endpoint;
use ostrya_remote::{
    Error, ErrorCode, PullBody, PullSession, Result, StreamSession, StreamSessionOptions,
};

/// The capacity of each pipe. It is smaller than a large body, so the server
/// waits for the client to read.
const PIPE_CAP: usize = 16 * 1024;

/// Returns the selector of `entries`, each a pattern with an optional `!`.
fn selector<S: AsRef<str>>(entries: &[S]) -> RefSelector {
    RefSelector::parse(entries.iter().map(AsRef::as_ref)).unwrap()
}

/// The time bound of each test.
const LIMIT: Duration = Duration::from_secs(30);

// ---------------------------------------------------------------------------
// A bounded pipe.
// ---------------------------------------------------------------------------

struct PipeState {
    buf: VecDeque<u8>,
    writer_closed: bool,
    reader_closed: bool,
    read_waker: Option<Waker>,
    write_waker: Option<Waker>,
}

/// The write half of a bounded pipe. After a drop of this half, the reader
/// reads end of file.
struct PipeWriter(Arc<Mutex<PipeState>>);

/// The read half of a bounded pipe. After a drop of this half, each later
/// write fails with `BrokenPipe`.
struct PipeReader(Arc<Mutex<PipeState>>);

fn pipe() -> (PipeWriter, PipeReader) {
    let state = Arc::new(Mutex::new(PipeState {
        buf: VecDeque::new(),
        writer_closed: false,
        reader_closed: false,
        read_waker: None,
        write_waker: None,
    }));
    (PipeWriter(state.clone()), PipeReader(state))
}

impl AsyncWrite for PipeWriter {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let mut st = self.0.lock().unwrap();
        if st.reader_closed {
            return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()));
        }
        let room = PIPE_CAP - st.buf.len();
        if room == 0 {
            st.write_waker = Some(cx.waker().clone());
            return Poll::Pending;
        }
        let n = room.min(buf.len());
        st.buf.extend(&buf[..n]);
        if let Some(w) = st.read_waker.take() {
            w.wake();
        }
        Poll::Ready(Ok(n))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        Poll::Ready(Ok(()))
    }
}

impl Drop for PipeWriter {
    fn drop(&mut self) {
        let mut st = self.0.lock().unwrap();
        st.writer_closed = true;
        if let Some(w) = st.read_waker.take() {
            w.wake();
        }
    }
}

impl AsyncRead for PipeReader {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let mut st = self.0.lock().unwrap();
        if st.buf.is_empty() {
            if st.writer_closed {
                return Poll::Ready(Ok(0));
            }
            st.read_waker = Some(cx.waker().clone());
            return Poll::Pending;
        }
        let n = buf.len().min(st.buf.len());
        for (dst, src) in buf[..n].iter_mut().zip(st.buf.drain(..n)) {
            *dst = src;
        }
        if let Some(w) = st.write_waker.take() {
            w.wake();
        }
        Poll::Ready(Ok(n))
    }
}

impl Drop for PipeReader {
    fn drop(&mut self) {
        let mut st = self.0.lock().unwrap();
        st.reader_closed = true;
        if let Some(w) = st.write_waker.take() {
            w.wake();
        }
    }
}

// ---------------------------------------------------------------------------
// The scripted server.
// ---------------------------------------------------------------------------

/// The server end of a session.
struct Server {
    reader: FrameReader<PipeReader>,
    writer: FrameWriter<PipeWriter>,
}

impl Server {
    async fn recv(&mut self) -> Option<Message> {
        self.reader.read_message().await.unwrap()
    }

    async fn send(&mut self, msg: &Message) {
        self.writer.write_message(msg).await.unwrap();
        self.writer.flush().await.unwrap();
    }

    /// Reads `PullHello` and replies with `version`.
    async fn hello(&mut self, version: u32) {
        match self.recv().await {
            Some(Message::PullHello(hello)) => assert_eq!(hello.version, PULL_PROTOCOL_VERSION),
            other => panic!("{other:?}"),
        }
        self.send(&Message::PullHelloReply(PullHelloReply { version }))
            .await;
    }

    /// Reads one `Get` and returns its path.
    async fn path(&mut self) -> String {
        match self.recv().await {
            Some(Message::Get(path)) => path,
            other => panic!("{other:?}"),
        }
    }

    /// Replies with `found` set to `true` and with `len`. Then sends `body` in
    /// chunks of `chunk` bytes, and then the end of the body.
    async fn body(&mut self, len: Option<u64>, body: &[u8], chunk: usize) {
        self.send(&Message::GetReply(GetReply { found: true, len }))
            .await;
        for piece in body.chunks(chunk) {
            self.writer.write_object_data(piece).await.unwrap();
        }
        self.writer.end_object().await.unwrap();
        self.writer.flush().await.unwrap();
    }

    /// Reads one `ListRefs` with no `collections` key and returns its
    /// entries.
    async fn list_refs(&mut self) -> Vec<String> {
        let request = self.list_refs_request().await;
        assert_eq!(request.collections, None);
        request.refs
    }

    /// Reads one `ListRefs` and returns it.
    async fn list_refs_request(&mut self) -> ListRefsRequest {
        match self.recv().await {
            Some(Message::ListRefs(request)) => request,
            other => panic!("{other:?}"),
        }
    }

    async fn not_found(&mut self) {
        self.send(&Message::GetReply(GetReply {
            found: false,
            len: None,
        }))
        .await;
    }

    async fn error(&mut self, code: ErrorCode, message: &str) {
        self.send(&Message::Error(error_message(code, message)))
            .await;
    }
}

fn error_message(code: ErrorCode, message: &str) -> ErrorMessage {
    ErrorMessage {
        code,
        message: message.to_owned(),
        missing: Vec::new(),
        current: None,
    }
}

/// The two ends of a session: the streams of the client and the server.
fn ends() -> ((PipeReader, PipeWriter), Server) {
    let (to_server, server_in) = pipe();
    let (server_out, from_server) = pipe();
    (
        (from_server, to_server),
        Server {
            reader: FrameReader::new(server_in),
            writer: FrameWriter::new(server_out),
        },
    )
}

fn options(max_outstanding: Option<usize>) -> StreamSessionOptions {
    StreamSessionOptions {
        agent: Some("pull-session-test".to_owned()),
        max_outstanding,
    }
}

/// Runs the client and the server together within the time bound.
fn run<C, S, T>(client: C, server: S) -> T
where
    C: Future<Output = T>,
    S: Future<Output = ()>,
{
    ostrya_rt::block_on(future::or(
        async {
            let (out, ()) = future::zip(client, server).await;
            out
        },
        async {
            ostrya_rt::Timer::after(LIMIT).await;
            panic!("the session took longer than {LIMIT:?}");
        },
    ))
}

/// One call of a test client, as a boxed future.
type Call<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;

/// Polls every future of `futures` until each is done, and returns their
/// outputs in order.
async fn join_all<T>(futures: Vec<Call<'_, T>>) -> Vec<T> {
    let mut futures: Vec<_> = futures.into_iter().map(Some).collect();
    let mut outputs: Vec<Option<T>> = futures.iter().map(|_| None).collect();
    future::poll_fn(|cx| {
        let mut pending = false;
        for (slot, out) in futures.iter_mut().zip(outputs.iter_mut()) {
            if let Some(fut) = slot {
                match fut.as_mut().poll(cx) {
                    Poll::Ready(value) => {
                        *out = Some(value);
                        *slot = None;
                    }
                    Poll::Pending => pending = true,
                }
            }
        }
        if pending {
            Poll::Pending
        } else {
            Poll::Ready(())
        }
    })
    .await;
    outputs.into_iter().map(Option::unwrap).collect()
}

async fn read_all(mut body: PullBody) -> io::Result<Vec<u8>> {
    let mut out = Vec::new();
    body.read_to_end(&mut out).await?;
    Ok(out)
}

/// The error of the session that a failed read of a body carries.
fn carried(e: io::Error) -> Error {
    *e.into_inner()
        .expect("the read error carries an error")
        .downcast::<Error>()
        .expect("the read error carries the error of the session")
}

fn body_of(path: &str) -> Vec<u8> {
    path.bytes().cycle().take(100 + path.len() * 1000).collect()
}

// ---------------------------------------------------------------------------
// Tests.
// ---------------------------------------------------------------------------

/// Eight concurrent calls keep eight `Get` frames in flight. The server reads
/// all eight before it answers one. Each reply goes to the call of its place,
/// also a not-found reply.
#[test]
fn concurrent_calls_share_the_pipeline_in_order() {
    let paths: Vec<String> = (0..8).map(|i| format!("objects/{i:02}/file")).collect();
    let ((input, output), mut server) = ends();
    let expected = paths.clone();
    let results = run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let calls: Vec<Call<'_, Option<Vec<u8>>>> = paths
                .iter()
                .map(|path| {
                    let session = &session;
                    Box::pin(async move {
                        match session.get(path, u64::MAX).await.unwrap() {
                            Some(body) => Some(read_all(body).await.unwrap()),
                            None => None,
                        }
                    }) as Call<'_, _>
                })
                .collect();
            let results = join_all(calls).await;
            session.finish().await.unwrap();
            results
        },
        async {
            server.hello(1).await;
            let mut seen = Vec::new();
            for _ in 0..8 {
                seen.push(server.path().await);
            }
            // The frames went on the wire in some order of the places. Each
            // reply answers the frame of its turn.
            let mut sorted = seen.clone();
            sorted.sort();
            assert_eq!(sorted, expected);
            for path in &seen {
                if path.ends_with("03/file") {
                    server.not_found().await;
                } else {
                    let body = body_of(path);
                    server.body(Some(body.len() as u64), &body, 1000).await;
                }
            }
            assert!(server.recv().await.is_none());
        },
    );
    for (path, got) in paths.iter().zip(results) {
        if path.ends_with("03/file") {
            assert_eq!(got, None);
        } else {
            assert_eq!(got.unwrap(), body_of(path), "{path}");
        }
    }
}

/// When the session reads the chunk that ends a body, it moves to the next
/// reply, also while the caller still holds that body.
#[test]
fn a_later_reply_arrives_while_the_caller_holds_a_body_read_to_its_end() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let mut first = session.get("a", 100).await.unwrap().unwrap();
            let mut bytes = Vec::new();
            first.read_to_end(&mut bytes).await.unwrap();
            assert_eq!(bytes, b"first");
            // `first` is still held.
            let second = session.get("b", 100).await.unwrap().unwrap();
            assert_eq!(second.len(), None);
            assert_eq!(read_all(second).await.unwrap(), b"second");
            drop(first);
            session.finish().await.unwrap();
        },
        async {
            server.hello(1).await;
            assert_eq!(server.path().await, "a");
            server.body(Some(5), b"first", 2).await;
            assert_eq!(server.path().await, "b");
            server.body(None, b"second", 4).await;
            assert!(server.recv().await.is_none());
        },
    );
}

/// A stated length that differs from the sum of the chunks is
/// `Error::Protocol` in both directions. It also ends the session.
#[test]
fn a_stated_length_that_differs_from_the_body_is_protocol() {
    for (stated, body) in [(10u64, &b"short"[..]), (3, &b"longer"[..])] {
        let ((input, output), mut server) = ends();
        run(
            async {
                let session = StreamSession::over_stream(input, output, options(None))
                    .await
                    .unwrap();
                let body = session.get("x", 100).await.unwrap().unwrap();
                assert_eq!(body.len(), Some(stated));
                let e = carried(read_all(body).await.unwrap_err());
                assert!(matches!(e, Error::Protocol(_)), "{e:?}");
                let later = session.get("y", 100).await.unwrap_err();
                assert_eq!(later.to_string(), e.to_string());
                assert!(matches!(session.finish().await, Err(Error::Protocol(_))));
            },
            async {
                server.hello(1).await;
                server.path().await;
                server.body(Some(stated), body, 100).await;
            },
        );
    }
}

/// A stated length that is more than the cap of the call ends the session
/// before the client reads the body. A body with no stated length ends the
/// session at the chunk that passes the cap.
#[test]
fn a_body_over_the_cap_ends_the_session() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let e = session.get("big", 4).await.unwrap_err();
            assert!(
                matches!(&e, Error::LimitExceeded(m) if m.contains("big")),
                "{e:?}"
            );
            let later = session.get("other", 4).await.unwrap_err();
            assert!(matches!(later, Error::LimitExceeded(_)), "{later:?}");
            assert_eq!(later.to_string(), e.to_string());
        },
        async {
            server.hello(1).await;
            server.path().await;
            server
                .send(&Message::GetReply(GetReply {
                    found: true,
                    len: Some(5),
                }))
                .await;
            // The client reads no body and closes its output.
            assert!(server.recv_or_eof().await);
        },
    );

    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let body = session.get("big", 4).await.unwrap().unwrap();
            let e = carried(read_all(body).await.unwrap_err());
            assert!(matches!(e, Error::LimitExceeded(_)), "{e:?}");
        },
        async {
            server.hello(1).await;
            server.path().await;
            // The writes after the client dropped its input fail.
            server
                .send(&Message::GetReply(GetReply {
                    found: true,
                    len: None,
                }))
                .await;
            let _ = server.writer.write_object_data(b"12345").await;
            let _ = server.writer.flush().await;
        },
    );
}

impl Server {
    /// Waits for the end of the input of the server, and returns `true` if it
    /// came. A read error also counts as the end.
    async fn recv_or_eof(&mut self) -> bool {
        matches!(self.reader.read_message().await, Ok(None) | Err(_))
    }
}

/// A `get` future that is dropped after it takes its place ends the session.
/// A body dropped before its end also ends the session. Later calls fail with
/// the same error.
#[test]
fn a_dropped_call_or_body_ends_the_session() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            {
                let mut call = Box::pin(session.get("dropped", 100));
                // One poll takes the place and writes the frame.
                assert!(future::poll_once(&mut call).await.is_none());
            }
            let e = session.get("later", 100).await.unwrap_err();
            assert!(
                matches!(&e, Error::InvalidInput(m) if m.contains("dropped")),
                "{e:?}"
            );
            assert!(matches!(
                session.finish().await,
                Err(Error::InvalidInput(_))
            ));
        },
        async {
            server.hello(1).await;
            assert_eq!(server.path().await, "dropped");
            assert!(server.recv_or_eof().await);
        },
    );

    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let mut body = session.get("held", 100).await.unwrap().unwrap();
            let mut two = [0u8; 2];
            body.read_exact(&mut two).await.unwrap();
            drop(body);
            let e = session.get("later", 100).await.unwrap_err();
            assert!(
                matches!(&e, Error::InvalidInput(m) if m.contains("body")),
                "{e:?}"
            );
        },
        async {
            server.hello(1).await;
            server.path().await;
            server.body(Some(6), b"abcdef", 2).await;
        },
    );
}

/// An `Error` message from the server is the error of the call. Each later
/// call repeats its code and its message. An I/O error repeats its kind and
/// its message.
#[test]
fn later_calls_repeat_the_first_error() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let (first, second) = future::zip(session.get("a", 100), session.get("b", 100)).await;
            assert!(matches!(&first, Err(Error::Internal(m)) if m == "cannot read a"));
            assert!(matches!(&second, Err(Error::Internal(m)) if m == "cannot read a"));
            let third = session.get("c", 100).await.unwrap_err();
            assert_eq!(third.code(), Some(ErrorCode::Internal));
            assert_eq!(third.to_string(), "internal: cannot read a");
            assert!(matches!(session.finish().await, Err(Error::Internal(_))));
        },
        async {
            server.hello(1).await;
            server.path().await;
            server.error(ErrorCode::Internal, "cannot read a").await;
        },
    );

    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let first = session.get("a", 100).await.unwrap_err();
            let Error::Io(io) = &first else {
                panic!("{first:?}");
            };
            assert_eq!(io.kind(), io::ErrorKind::UnexpectedEof);
            let later = session.get("b", 100).await.unwrap_err();
            let Error::Io(again) = &later else {
                panic!("{later:?}");
            };
            assert_eq!(again.kind(), io::ErrorKind::UnexpectedEof);
            assert_eq!(again.to_string(), io.to_string());
        },
        async {
            server.hello(1).await;
            server.path().await;
            // The server ends its output with no reply.
            let Server { reader, writer } = server;
            drop(writer);
            drop(reader);
        },
    );
}

/// After the abandon marker, the session reads the `Error` message. The read
/// of the body fails with the code of that message.
#[test]
fn an_abandoned_body_gives_the_code_of_its_error() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let body = session.get("a", 100).await.unwrap().unwrap();
            let e = carried(read_all(body).await.unwrap_err());
            assert!(
                matches!(&e, Error::Internal(m) if m == "read failed"),
                "{e:?}"
            );
            let later = session.get("b", 100).await.unwrap_err();
            assert!(matches!(later, Error::Internal(_)), "{later:?}");
        },
        async {
            server.hello(1).await;
            server.path().await;
            server
                .send(&Message::GetReply(GetReply {
                    found: true,
                    len: Some(10),
                }))
                .await;
            server.writer.write_object_data(b"abc").await.unwrap();
            server
                .writer
                .abandon_body(&error_message(ErrorCode::Internal, "read failed"))
                .await
                .unwrap();
            server.writer.flush().await.unwrap();
        },
    );
}

/// The client continues after a reply of version 1. It refuses a reply of a
/// version that it does not speak. An `Error` message at the hello is
/// returned as the `Error` variant of its code.
#[test]
fn the_hello_reply_gives_the_version_of_the_session() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            assert!(session.get("config", 100).await.unwrap().is_none());
            session.finish().await.unwrap();
        },
        async {
            server.hello(1).await;
            server.path().await;
            server.not_found().await;
            assert!(server.recv().await.is_none());
        },
    );

    for version in [0, PULL_PROTOCOL_VERSION + 1] {
        let ((input, output), mut server) = ends();
        run(
            async {
                match StreamSession::over_stream(input, output, options(None)).await {
                    Err(Error::VersionUnsupported(m)) => assert!(m.contains("version"), "{m}"),
                    Err(other) => panic!("{other:?}"),
                    Ok(_) => panic!("version {version} accepted"),
                }
            },
            async {
                server.hello(version).await;
                // The client sends no `Get`, and closes its output.
                assert!(server.recv().await.is_none());
            },
        );
    }

    let ((input, output), mut server) = ends();
    run(
        async {
            match StreamSession::over_stream(input, output, options(None)).await {
                Err(Error::VersionUnsupported(m)) => assert_eq!(m, "no such version"),
                Err(other) => panic!("{other:?}"),
                Ok(_) => panic!("accepted"),
            }
        },
        async {
            server.recv().await;
            server
                .error(ErrorCode::VersionUnsupported, "no such version")
                .await;
        },
    );
}

/// The session raises a pipeline depth of 0 to 1, so the server sees one
/// `Get` at a time.
#[test]
fn a_depth_of_zero_keeps_one_get_in_flight() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(Some(0)))
                .await
                .unwrap();
            let calls: Vec<Call<'_, Vec<u8>>> = ["a", "b", "c"]
                .into_iter()
                .map(|path| {
                    let session = &session;
                    Box::pin(async move {
                        read_all(session.get(path, 100).await.unwrap().unwrap())
                            .await
                            .unwrap()
                    }) as Call<'_, _>
                })
                .collect();
            let bodies = join_all(calls).await;
            assert_eq!(bodies, [b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]);
            session.finish().await.unwrap();
        },
        async {
            server.hello(1).await;
            for _ in 0..3 {
                let path = server.path().await;
                // No second `Get` waits while this one is in flight.
                let early = future::poll_once(server.reader.read_message()).await;
                assert!(early.is_none(), "a second Get came early: {early:?}");
                server.body(Some(1), path.as_bytes(), 1).await;
            }
            assert!(server.recv().await.is_none());
        },
    );
}

/// If the caller holds a body that it did not read to its end, `finish` ends
/// the session uncleanly and returns `InvalidInput`. The session drops its
/// input, and a later read of the held body repeats the error.
#[test]
fn finish_with_an_unread_body_is_an_unclean_end() {
    let ((input, output), mut server) = ends();
    let held = run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let mut body = session.get("a", 100).await.unwrap().unwrap();
            let e = session.finish().await.unwrap_err();
            assert!(
                matches!(&e, Error::InvalidInput(m) if m.contains("unread")),
                "{e:?}"
            );
            let mut bytes = Vec::new();
            let later = carried(body.read_to_end(&mut bytes).await.unwrap_err());
            assert_eq!(later.to_string(), e.to_string());
            assert!(bytes.is_empty(), "{bytes:?}");
            // The caller still holds the body while the server writes.
            body
        },
        async {
            server.hello(1).await;
            server.path().await;
            server.body(Some(3), b"abc", 3).await;
            assert!(server.recv_or_eof().await);
            let write = server.writer.write_message(&Message::Abort).await;
            assert!(
                matches!(&write, Err(Error::Io(e)) if e.kind() == io::ErrorKind::BrokenPipe),
                "the client kept its input open: {write:?}"
            );
        },
    );
    drop(held);
}

/// After the session fails, a read of a body fails with a repeat of the first
/// error and reads no more of the body.
#[test]
fn a_body_read_after_a_failure_repeats_the_failure() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let mut body = session.get("a", 100).await.unwrap().unwrap();
            {
                let mut call = Box::pin(session.get("b", 100));
                // One poll takes the place and writes the frame.
                assert!(future::poll_once(&mut call).await.is_none());
            }
            let mut bytes = Vec::new();
            let e = carried(body.read_to_end(&mut bytes).await.unwrap_err());
            assert!(
                matches!(&e, Error::InvalidInput(m) if m.contains("dropped")),
                "{e:?}"
            );
            assert!(bytes.is_empty(), "{bytes:?}");
        },
        async {
            server.hello(1).await;
            assert_eq!(server.path().await, "a");
            server.body(Some(3), b"abc", 3).await;
            assert_eq!(server.path().await, "b");
        },
    );
}

/// A session dropped while the caller holds a body closes its output, so the
/// server reads the end of its input.
#[test]
fn a_dropped_session_closes_its_output_while_a_body_is_held() {
    let ((input, output), mut server) = ends();
    let held = run(
        async {
            let session = StreamSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let body = session.get("a", 100).await.unwrap().unwrap();
            drop(session);
            body
        },
        async {
            server.hello(1).await;
            server.path().await;
            server.body(Some(3), b"abc", 3).await;
            assert!(server.recv().await.is_none());
        },
    );
    drop(held);
}

/// Returns the error of an open of a pull session that must fail.
fn refused(opened: Result<PullSession>) -> Error {
    match opened {
        Ok(_) => panic!("the session opened"),
        Err(e) => e,
    }
}

/// `connect` refuses a set field of the stream options for an HTTP endpoint,
/// before it checks the mirrors and before it builds the fetcher. The
/// fetcher refuses the `ftp` mirror, and the check of the mirrors refuses the
/// options with no mirror. The refusal of the stream options comes before
/// both.
#[test]
fn connect_refuses_stream_options_for_an_http_endpoint() {
    for http in [FetcherOptions::new("ftp://h/"), FetcherOptions::default()] {
        for (opts, message) in [
            (
                StreamSessionOptions {
                    agent: Some("agent".to_owned()),
                    max_outstanding: None,
                },
                "an HTTP pull takes no agent of a stream session",
            ),
            (
                StreamSessionOptions {
                    agent: None,
                    max_outstanding: Some(4),
                },
                "an HTTP pull takes no request limit of a stream session",
            ),
        ] {
            let e = refused(ostrya_rt::block_on(PullSession::connect(
                Endpoint::Http(http.clone()),
                opts,
            )));
            assert!(
                matches!(&e, Error::InvalidInput(m) if m.starts_with(message)),
                "{e:?}"
            );
        }
    }
    let e = refused(ostrya_rt::block_on(PullSession::connect(
        Endpoint::Http(FetcherOptions::new("ftp://h/")),
        StreamSessionOptions::default(),
    )));
    assert!(matches!(e, Error::Fetch(_)), "{e:?}");
}

/// `connect` refuses an HTTP endpoint that names no mirror.
#[test]
fn connect_refuses_an_http_endpoint_with_no_mirror() {
    let e = refused(ostrya_rt::block_on(PullSession::connect(
        Endpoint::Http(FetcherOptions::default()),
        StreamSessionOptions::default(),
    )));
    assert!(
        matches!(&e, Error::InvalidInput(m) if m == "the HTTP endpoint of a pull names no mirror"),
        "{e:?}"
    );
}

/// `connect` for an HTTP endpoint gives the fetcher of the endpoint. The
/// fetcher admits the request limit of the options, and at least 1. `finish`
/// of an HTTP session is `Ok`.
///
/// The mirror is cleartext and the fetcher follows no redirect and uses no
/// proxy, so the open reads no trust store. No server listens, and the open
/// sends no request.
#[test]
fn connect_for_http_gives_the_fetcher_and_its_limit() {
    for (asked, admitted) in [(5, 5), (0, 1)] {
        let mut http = FetcherOptions::new("http://127.0.0.1:9/");
        http.max_redirects = 0;
        http.proxy = Proxy::None;
        http.max_outstanding = asked;
        ostrya_rt::block_on(async {
            let session =
                PullSession::connect(Endpoint::Http(http), StreamSessionOptions::default())
                    .await
                    .unwrap();
            assert!(matches!(session, PullSession::Http(_)));
            assert_eq!(session.max_outstanding(), admitted);
            session.finish().await.unwrap();
        });
    }
}

/// `over_stream` gives a stream session with the request limit of the
/// options: 8 if the options give no number, and at least 1.
#[test]
fn over_stream_gives_the_limit_of_the_stream_session() {
    for (asked, admitted) in [(Some(3), 3), (None, 8), (Some(0), 1)] {
        let ((input, output), mut server) = ends();
        run(
            async {
                let session = PullSession::over_stream(input, output, options(asked))
                    .await
                    .unwrap();
                assert!(matches!(session, PullSession::Stream(_)));
                assert_eq!(session.max_outstanding(), admitted);
                session.finish().await.unwrap();
            },
            async {
                server.hello(1).await;
                assert!(server.recv().await.is_none());
            },
        );
    }
}

/// `fetch_summary` over a stream session asks for `summary.sig` and then for
/// `summary`, with both calls in flight together. It returns the summary
/// first. A file that the server does not serve is `None`.
#[test]
fn fetch_summary_over_a_stream_returns_both_files() {
    let summary = body_of("summary");
    let signature = body_of("summary.sig");
    for (sig_served, summary_served) in [(true, true), (false, true), (true, false)] {
        let ((input, output), mut server) = ends();
        let got = run(
            async {
                let session = PullSession::over_stream(input, output, options(None))
                    .await
                    .unwrap();
                let got = session.fetch_summary().await.unwrap();
                session.finish().await.unwrap();
                got
            },
            async {
                server.hello(1).await;
                // Both `Get` frames arrive before the first reply.
                assert_eq!(server.path().await, "summary.sig");
                assert_eq!(server.path().await, "summary");
                for (served, body) in [(sig_served, &signature), (summary_served, &summary)] {
                    if served {
                        server.body(Some(body.len() as u64), body, 1000).await;
                    } else {
                        server.not_found().await;
                    }
                }
                assert!(server.recv().await.is_none());
            },
        );
        assert_eq!(got.0, summary_served.then(|| summary.clone()));
        assert_eq!(got.1, sig_served.then(|| signature.clone()));
    }
}

/// `fetch_summary` caps each file at 64 MiB. A stated length over the cap
/// ends the session with `LimitExceeded` before the client reads the body.
#[test]
fn fetch_summary_refuses_a_stated_length_over_64_mib() {
    const CAP: u64 = 64 * 1024 * 1024;
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let e = session.fetch_summary().await.unwrap_err();
            assert!(
                matches!(&e, Error::LimitExceeded(m) if m.contains(&format!("over the limit {CAP}"))),
                "{e:?}"
            );
        },
        async {
            server.hello(1).await;
            server.path().await;
            server.path().await;
            server
                .send(&Message::GetReply(GetReply {
                    found: true,
                    len: Some(CAP + 1),
                }))
                .await;
            // The client reads no body and closes its output.
            assert!(server.recv_or_eof().await);
        },
    );
}

/// A `fetch_refs` and a `get` in flight on one session keep the order of
/// their frames. The server reads both frames before it answers, and each
/// call gets the body of its own reply. The test runs both orders.
#[test]
fn fetch_refs_and_get_keep_their_order() {
    let listing = body_of("listing");
    let config = body_of("config");
    for refs_first in [false, true] {
        let ((input, output), mut server) = ends();
        let (refs, got) = run(
            async {
                let session = PullSession::over_stream(input, output, options(None))
                    .await
                    .unwrap();
                let PullSession::Stream(stream) = &session else {
                    unreachable!("over_stream gives a stream session");
                };
                let get = async {
                    let body = stream.get("config", u64::MAX).await.unwrap().unwrap();
                    read_all(body).await.unwrap()
                };
                let refs = async {
                    session
                        .fetch_refs(&selector(&["a", "b/c"]), None)
                        .await
                        .unwrap()
                };
                let out = if refs_first {
                    future::zip(refs, get).await
                } else {
                    let (got, refs) = future::zip(get, refs).await;
                    (refs, got)
                };
                session.finish().await.unwrap();
                out
            },
            async {
                server.hello(1).await;
                let prefixes = vec!["a".to_owned(), "b/c".to_owned()];
                if refs_first {
                    assert_eq!(server.list_refs().await, prefixes);
                    assert_eq!(server.path().await, "config");
                    server
                        .body(Some(listing.len() as u64), &listing, 1000)
                        .await;
                    server.body(Some(config.len() as u64), &config, 1000).await;
                } else {
                    assert_eq!(server.path().await, "config");
                    assert_eq!(server.list_refs().await, prefixes);
                    server.body(Some(config.len() as u64), &config, 1000).await;
                    server
                        .body(Some(listing.len() as u64), &listing, 1000)
                        .await;
                }
                assert!(server.recv().await.is_none());
            },
        );
        assert_eq!(refs, Some(listing.clone()), "{refs_first}");
        assert_eq!(got, config, "{refs_first}");
    }
}

/// `fetch_refs` sends an empty entry list as it is, and reads the listing in
/// chunks.
#[test]
fn fetch_refs_sends_an_empty_list_and_reads_the_listing() {
    let listing = body_of("all");
    let ((input, output), mut server) = ends();
    let got = run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let got = session
                .fetch_refs(&selector::<&str>(&[]), None)
                .await
                .unwrap();
            session.finish().await.unwrap();
            got
        },
        async {
            server.hello(1).await;
            assert!(server.list_refs().await.is_empty());
            server.body(Some(listing.len() as u64), &listing, 700).await;
            assert!(server.recv().await.is_none());
        },
    );
    assert_eq!(got, Some(listing));
}

/// `fetch_refs` caps the listing at `MAX_REF_LISTING`. A stated length over
/// the cap ends the session with `LimitExceeded` before the client reads the
/// body.
#[test]
fn fetch_refs_refuses_a_stated_length_over_the_cap() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let e = session
                .fetch_refs(&selector(&["main"]), None)
                .await
                .unwrap_err();
            assert!(
                matches!(&e, Error::LimitExceeded(m)
                    if m.contains(&format!("over the limit {MAX_REF_LISTING}"))),
                "{e:?}"
            );
        },
        async {
            server.hello(1).await;
            server.list_refs().await;
            server
                .send(&Message::GetReply(GetReply {
                    found: true,
                    len: Some(MAX_REF_LISTING + 1),
                }))
                .await;
            // The client reads no body and closes its output.
            assert!(server.recv_or_eof().await);
        },
    );
}

/// A server that refuses a listing over its cap sends `limit-exceeded`.
/// `fetch_refs` returns `LimitExceeded`, and a later call repeats it.
#[test]
fn fetch_refs_gives_the_limit_exceeded_of_the_server() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let e = session
                .fetch_refs(&selector::<&str>(&[]), None)
                .await
                .unwrap_err();
            assert!(
                matches!(&e, Error::LimitExceeded(m) if m == "too large"),
                "{e:?}"
            );
            let e = session
                .fetch_refs(&selector::<&str>(&[]), None)
                .await
                .unwrap_err();
            assert!(
                matches!(&e, Error::LimitExceeded(m) if m == "too large"),
                "{e:?}"
            );
        },
        async {
            server.hello(1).await;
            server.list_refs().await;
            server.error(ErrorCode::LimitExceeded, "too large").await;
            assert!(server.recv_or_eof().await);
        },
    );
}

/// An entry over the limit of 4,096 bytes or 256 parts is `InvalidInput`. The
/// call writes nothing, and the session stays usable: the next frame that the
/// server reads is the `Get` of a later call.
#[test]
fn fetch_refs_refuses_an_entry_over_a_limit_and_writes_nothing() {
    let ((input, output), mut server) = ends();
    let config = body_of("config");
    let got = run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let parts = |n: usize| vec!["a"; n].join("/");
            for bad in [
                parts(256 + 1),
                "a".repeat(4096 + 1),
                format!("!{}", "a".repeat(4096)),
            ] {
                let e = session
                    .fetch_refs(&selector(&["main", bad.as_str()]), None)
                    .await
                    .unwrap_err();
                assert!(matches!(e, Error::InvalidInput(_)), "{e:?}");
            }
            let PullSession::Stream(stream) = &session else {
                unreachable!("over_stream gives a stream session");
            };
            let body = stream.get("config", u64::MAX).await.unwrap().unwrap();
            let got = read_all(body).await.unwrap();
            session.finish().await.unwrap();
            got
        },
        async {
            server.hello(1).await;
            assert_eq!(server.path().await, "config");
            server.body(Some(config.len() as u64), &config, 1000).await;
            assert!(server.recv().await.is_none());
        },
    );
    assert_eq!(got, config);
}

/// A `GetReply` whose `found` is `false` in reply to `ListRefs` is
/// `Protocol`. It ends the session, and a later call repeats it.
#[test]
fn a_not_found_reply_to_list_refs_is_protocol() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let e = session
                .fetch_refs(&selector(&["main"]), None)
                .await
                .unwrap_err();
            assert!(
                matches!(&e, Error::Protocol(m) if m.contains("ListRefs")),
                "{e:?}"
            );
            let PullSession::Stream(stream) = &session else {
                unreachable!("over_stream gives a stream session");
            };
            let e = stream.get("config", 1).await.unwrap_err();
            assert!(matches!(e, Error::Protocol(_)), "{e:?}");
        },
        async {
            server.hello(1).await;
            server.list_refs().await;
            server.not_found().await;
            assert!(server.recv_or_eof().await);
        },
    );
}

/// A `GetReply` that states no length in reply to `ListRefs` is `Protocol`.
/// It ends the session before the client reads the body, and a later call
/// repeats it.
#[test]
fn a_reply_to_list_refs_with_no_length_is_protocol() {
    let ((input, output), mut server) = ends();
    run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let e = session
                .fetch_refs(&selector(&["main"]), None)
                .await
                .unwrap_err();
            assert!(
                matches!(&e, Error::Protocol(m) if m.contains("no length")),
                "{e:?}"
            );
            let PullSession::Stream(stream) = &session else {
                unreachable!("over_stream gives a stream session");
            };
            let e = stream.get("config", 1).await.unwrap_err();
            assert!(
                matches!(&e, Error::Protocol(m) if m.contains("no length")),
                "{e:?}"
            );
        },
        async {
            server.hello(1).await;
            server.list_refs().await;
            server
                .send(&Message::GetReply(GetReply {
                    found: true,
                    len: None,
                }))
                .await;
            assert!(server.recv_or_eof().await);
        },
    );
}

/// Returns a session over HTTP to an address where no server listens. The
/// fetcher makes no retry, so a request fails at once.
fn dead_http_session() -> PullSession {
    let mut http = FetcherOptions::new("http://127.0.0.1:9/");
    http.max_redirects = 0;
    http.max_retries = 0;
    http.proxy = Proxy::None;
    ostrya_rt::block_on(PullSession::connect(
        Endpoint::Http(http),
        StreamSessionOptions::default(),
    ))
    .unwrap()
}

/// Returns `count` distinct entries, which alternate between a positive
/// pattern and a negative pattern.
fn mixed_entries(count: usize) -> Vec<String> {
    (0..count)
        .map(|n| {
            if n % 2 == 0 {
                format!("r{n}")
            } else {
                format!("!r{n}")
            }
        })
        .collect()
}

/// Over HTTP, an entry over a limit, more than 256 entries after the removal
/// of exact duplicates, and a request target over 16 KiB are `InvalidInput`.
/// The call sends no request. No server listens on the address, so a request
/// fails with `Fetch`.
#[test]
fn fetch_refs_over_http_refuses_bad_input_before_a_request() {
    let session = dead_http_session();
    let many = mixed_entries(257);
    // 256 entries of 64 bytes take 256 * 73 bytes of query, with the key
    // and the separator, which is more than 16 KiB.
    let long = (0..256)
        .map(|n| format!("{n:0>64}"))
        .collect::<Vec<String>>();
    // Four entries of 700 `é` are 4,200 bytes each when encoded. The four
    // entries together are more than 16 KiB, and each entry is under 4,096
    // bytes.
    let accents: Vec<String> = (0..4).map(|n| format!("{}{n}", "é".repeat(700))).collect();
    let parts = "a/".repeat(256) + "a";
    let bytes = "a".repeat(4096 + 1);
    let negative_bytes = format!("!{}", "a".repeat(4096));
    ostrya_rt::block_on(async {
        for (case, entries) in [
            ("257 entries", &many),
            ("long target", &long),
            ("escaped target", &accents),
            ("257 parts", &vec![parts]),
            ("4097 bytes", &vec![bytes]),
            ("negative 4097 bytes", &vec![negative_bytes]),
        ] {
            let e = session
                .fetch_refs(&selector(entries), None)
                .await
                .unwrap_err();
            assert!(matches!(e, Error::InvalidInput(_)), "{case}: {e:?}");
        }
        // 300 copies of one entry are one entry, and the client sends the
        // request.
        let e = session
            .fetch_refs(&selector(&["main"; 300]), None)
            .await
            .unwrap_err();
        assert!(matches!(e, Error::Fetch(_)), "{e:?}");
        // 256 distinct entries, of both kinds, pass the client checks.
        let e = session
            .fetch_refs(&selector(&many[..256]), None)
            .await
            .unwrap_err();
        assert!(matches!(e, Error::Fetch(_)), "{e:?}");
    });
    ostrya_rt::block_on(session.finish()).unwrap();
}

/// Over a stream session, more than 256 entries after the removal of exact
/// duplicates are `InvalidInput`. The count holds the positive and the
/// negative entries together. The call writes nothing. The client removes
/// exact duplicates before it sends `ListRefs`, puts the positive entries
/// first, and keeps an entry that another entry covers.
#[test]
fn fetch_refs_over_a_stream_counts_the_entries_that_stay() {
    let ((input, output), mut server) = ends();
    let listing = body_of("listing");
    let got = run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let many = mixed_entries(257);
            let e = session
                .fetch_refs(&selector(&many), None)
                .await
                .unwrap_err();
            assert!(matches!(e, Error::InvalidInput(_)), "{e:?}");
            let mut entries = vec!["!a/*", "a/b", "main", "a", "!main"];
            entries.extend(["main"; 300]);
            let got = session.fetch_refs(&selector(&entries), None).await.unwrap();
            session.finish().await.unwrap();
            got
        },
        async {
            server.hello(1).await;
            assert_eq!(
                server.list_refs().await,
                ["a/b", "main", "a", "!a/*", "!main"]
            );
            server.body(Some(listing.len() as u64), &listing, 700).await;
            assert!(server.recv().await.is_none());
        },
    );
    assert_eq!(got, Some(listing));
}

/// Over a stream session, a selector of the collection refs goes in the
/// `collections` key of `ListRefs`, with the rules of the entries of the
/// local refs: positive entries first, and an exact duplicate removed. A
/// selector with no entry is a present empty list, and no selector sends no
/// key. The two lists share the limit of 256 entries, and a call over it
/// writes nothing.
#[test]
fn fetch_refs_over_a_stream_sends_the_collection_entries() {
    let ((input, output), mut server) = ends();
    let listing = body_of("listing");
    let served = listing.clone();
    let got = run(
        async {
            let session = PullSession::over_stream(input, output, options(None))
                .await
                .unwrap();
            let many = mixed_entries(200);
            let e = session
                .fetch_refs(&selector(&many), Some(&selector(&many[..57])))
                .await
                .unwrap_err();
            assert!(matches!(e, Error::InvalidInput(_)), "{e:?}");
            let mut got = Vec::new();
            let collections = selector(&["!org.b/**", "org.a/*", "org.a/*"]);
            for collections in [Some(&collections), Some(&selector::<&str>(&[])), None] {
                let listing = session
                    .fetch_refs(&selector(&["main"]), collections)
                    .await
                    .unwrap();
                got.push(listing);
            }
            session.finish().await.unwrap();
            got
        },
        async {
            server.hello(1).await;
            let entries =
                |list: &[&str]| -> Vec<String> { list.iter().map(|e| (*e).to_owned()).collect() };
            for collections in [
                Some(entries(&["org.a/*", "!org.b/**"])),
                Some(Vec::new()),
                None,
            ] {
                assert_eq!(
                    server.list_refs_request().await,
                    ListRefsRequest {
                        refs: entries(&["main"]),
                        collections,
                    }
                );
                server.body(Some(served.len() as u64), &served, 700).await;
            }
            assert!(server.recv().await.is_none());
        },
    );
    assert_eq!(got, vec![Some(listing); 3]);
}