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
//! The client session of a pull: the pipeline of `Get` and `ListRefs` frames
//! and the bodies of the replies.

use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashSet};
use std::future::{Future, poll_fn};
use std::io;
use std::pin::Pin;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Waker, ready};
use std::time::Duration;

use futures_io::{AsyncRead, AsyncWrite};
use futures_lite::io::{AsyncWriteExt, BufReader};
use ostrya_core::RefSelector;
use ostrya_fetch::Priority;
use ostrya_fetch::gate::{Gate, Permit};

use super::stream::{Input, Output};
use crate::error::{Error, Result};
use crate::proto::{
    FrameReader, FrameWriter, GetReply, Kind, ListRefsRequest, MAX_REF_ENTRY_LEN,
    MAX_REF_ENTRY_PARTS, MAX_REF_PATTERNS, MIN_FRAME_LIMIT, Message, PULL_PROTOCOL_VERSION,
    PullHello, Step, encode_frame, protocol,
};
use crate::transport::Transport;

/// The buffer size of the input of the session.
const STREAM_BUFFER: usize = 64 * 1024;

/// The most calls that hold a place at a time if the options give no number.
const DEFAULT_OUTSTANDING: usize = 8;

type Reader = FrameReader<BufReader<Input>>;
type ReadFuture = Pin<Box<dyn Future<Output = Result<Option<Message>>> + Send>>;

/// The options of a stream session.
#[derive(Debug, Clone, Default)]
pub struct StreamSessionOptions {
    /// The `agent` value that the session sends in [`PullHello`].
    ///
    /// The default is `ostrya/<version>`, with the version of this crate.
    pub agent: Option<String>,
    /// The most [`get`](StreamSession::get) and
    /// [`list_refs`](StreamSession::list_refs) calls that hold a place in the
    /// [pipeline](StreamSession#pipeline) at a time.
    ///
    /// The default is 8. The session raises a value of 0 to 1.
    pub max_outstanding: Option<usize>,
}

/// A client session of a pull, which reads the files and ref listings of a
/// server.
///
/// [`connect`](StreamSession::connect) opens a session over ssh, and
/// [`over_stream`](StreamSession::over_stream) opens one over a pair of byte
/// streams. The session is `Send + Sync`. Concurrent
/// [`get`](StreamSession::get) and [`list_refs`](StreamSession::list_refs)
/// calls share the [pipeline](StreamSession#pipeline), and the replies come
/// in the order of the frames.
///
/// If the session is dropped without [`finish`](StreamSession::finish), it
/// sends nothing more and closes its output, so the server reads the end of
/// its input. This is also true while the caller holds a [`PullBody`]. If
/// [`connect`](StreamSession::connect) opened the session, the drop then drops
/// the ssh client without a wait.
///
/// # Pipeline
///
/// The session opens with [`PullHello`]. It asks for files by their path
/// with [`get`](StreamSession::get), and for ref listings with
/// [`list_refs`](StreamSession::list_refs). All requests share one stream as
/// a pipeline. A call takes its place and writes its frame under one lock, so
/// the frames go on the wire in the order of the places.
///
/// A reply carries no request id. The reply of a call is the next reply
/// after the reply of the call before it.
///
/// At most [`max_outstanding`](StreamSessionOptions::max_outstanding) calls
/// hold a place at a time. A call holds its place from the write of its
/// frame to the end of its reply.
///
/// If a [`get`](StreamSession::get) gets a [`GetReply`] whose `found` is
/// `false`, that `GetReply` is the end of the reply. For each other reply,
/// the end is the chunk that ends the body. When the session reads that
/// chunk, it moves to the next reply, also while the caller still holds the
/// [`PullBody`].
///
/// # Failures
///
/// Each of these events is a failure, and a failure ends the session:
///
/// - an `Error` message from the server
/// - a reply of a kind that the session does not expect
/// - a [`GetReply`] whose `found` is `false`, or that states no length, in
///   reply to `ListRefs`
/// - a stated length that is more than the cap of the call, or that is
///   different from the sum of the chunks
/// - a body that is longer than the cap of the call
/// - a failed read or write
/// - a drop of a `get` or `list_refs` future after the call took its place
/// - a drop of a [`PullBody`] before its end
/// - a [`finish`](StreamSession::finish) while the body of a reply is not read
///   to its end
///
/// After a failure, each later call and each later read of a body fails. Its
/// error has the variant and the message of the first failure.
pub struct StreamSession {
    inner: StreamInner,
}

struct StreamInner {
    shared: Arc<Shared>,
    /// The number of calls that hold a place in the pipeline at one time, at
    /// least 1.
    max_outstanding: usize,
    /// The ssh client, for a session that [`StreamSession::connect`] opened.
    /// The box keeps the session small.
    transport: Option<Box<Transport>>,
}

/// The state that the session, its calls, and its bodies share.
struct Shared {
    /// The places of the pipeline.
    places: Arc<Gate>,
    /// The order of the writes: one call writes at a time, in the order in
    /// which the calls arrived.
    writing: Arc<Gate>,
    write: Mutex<WriteSide>,
    read: Mutex<ReadSide>,
    /// The longest wait for a pending message after a failed write. `None`
    /// waits with no limit.
    pending_limit: Option<Duration>,
}

struct WriteSide {
    /// The output, which a call takes while it writes its `Get` frame. It is
    /// `None` after a write failed, after the session failed, or after the
    /// session ended.
    writer: Option<Output>,
    /// The place of the next call.
    next: u64,
}

struct ReadSide {
    /// The reader. The call whose reply is next takes it while it reads the
    /// head of its reply. The body of a found file reads it here, under the
    /// lock. The end of the session can then drop it also while the caller
    /// holds the body.
    reader: Option<Box<Reader>>,
    /// The read of the frame that follows the abandon marker of a body. It
    /// holds the reader.
    abandoned: Option<ReadFuture>,
    /// The place whose reply is next.
    turn: u64,
    /// The waker of each call that waits for its reply, by place.
    waiting: BTreeMap<u64, Waker>,
    /// The first failure of the session.
    failure: Option<Error>,
}

/// Returns a copy of `e` for a later call of a session that failed with `e`.
///
/// The copy has the variant and the message of `e`, and an I/O error keeps
/// its kind. Each other variant with no wire code becomes `InvalidInput`.
fn repeat(e: &Error) -> Error {
    match e {
        Error::Io(io) => Error::Io(io::Error::new(io.kind(), io.to_string())),
        Error::Transport(msg) => Error::Transport(msg.clone()),
        Error::InvalidInput(msg) => Error::InvalidInput(msg.clone()),
        other if other.code().is_some() => other.to_message().into(),
        other => Error::InvalidInput(other.to_string()),
    }
}

/// Returns the `io::Error` that a body read gives for `e`.
///
/// It carries `e`. Its kind is the kind of an I/O error, and `Other` for
/// each other error.
fn body_error(e: Error) -> io::Error {
    let kind = match &e {
        Error::Io(io) => io.kind(),
        _ => io::ErrorKind::Other,
    };
    io::Error::new(kind, e)
}

/// Returns the `ListRefs` request of a ref listing of `refs` and
/// `collections`, by the rules of `PullSession` `# Ref patterns`.
///
/// # Errors
///
/// [`Error::InvalidInput`] if an entry is over [`MAX_REF_ENTRY_LEN`] bytes,
/// with its `!` counted as one byte, or over [`MAX_REF_ENTRY_PARTS`] parts,
/// or if more than [`MAX_REF_PATTERNS`] entries stay in the two lists.
pub(super) fn wire_entries(
    refs: &RefSelector,
    collections: Option<&RefSelector>,
) -> Result<ListRefsRequest> {
    let mut count = 0;
    let refs = list_entries(refs, &mut count)?;
    let collections = collections
        .map(|selector| list_entries(selector, &mut count))
        .transpose()?;
    Ok(ListRefsRequest { refs, collections })
}

/// Returns the entries of one list of a request, and adds their number to
/// `count`, the number of entries of the request.
///
/// The positive entries come first, then the negative entries with their
/// `!`. Each exact duplicate of one kind is removed.
fn list_entries(selector: &RefSelector, count: &mut usize) -> Result<Vec<String>> {
    let mut seen = HashSet::new();
    let mut entries = Vec::new();
    let positive = selector.positive().iter().map(|p| (false, p.as_str()));
    let negative = selector.negative().iter().map(|p| (true, p.as_str()));
    for (is_negative, text) in positive.chain(negative) {
        if !seen.insert((is_negative, text)) {
            continue;
        }
        let len = text.len() + usize::from(is_negative);
        let parts = text.split('/').count();
        if len > MAX_REF_ENTRY_LEN || parts > MAX_REF_ENTRY_PARTS {
            return Err(Error::InvalidInput(format!(
                "a ref pattern entry has {len} bytes and {parts} parts, over the limits of \
                 {MAX_REF_ENTRY_LEN} bytes and {MAX_REF_ENTRY_PARTS} parts"
            )));
        }
        if *count == MAX_REF_PATTERNS {
            return Err(Error::InvalidInput(format!(
                "the ref listing names more than {MAX_REF_PATTERNS} distinct entries"
            )));
        }
        *count += 1;
        entries.push(if is_negative {
            format!("!{text}")
        } else {
            text.to_owned()
        });
    }
    Ok(entries)
}

fn eof(what: &str) -> Error {
    Error::Io(io::Error::new(
        io::ErrorKind::UnexpectedEof,
        format!("the session ended before {what}"),
    ))
}

/// Reads one message within `limit`. A failed read, an end of file, and a
/// read that takes longer than `limit` give `None`.
async fn read_pending(reader: &mut Reader, limit: Option<Duration>) -> Option<Message> {
    let read = async { reader.read_message().await.ok().flatten() };
    match limit {
        None => read.await,
        Some(limit) => {
            let timeout = async {
                ostrya_rt::Timer::after(limit).await;
                None
            };
            futures_lite::future::or(read, timeout).await
        }
    }
}

impl Shared {
    fn lock_read(&self) -> MutexGuard<'_, ReadSide> {
        self.read.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn lock_write(&self) -> MutexGuard<'_, WriteSide> {
        self.write.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Returns the repeat of the first failure if the session failed.
    fn check(&self) -> Result<()> {
        match &self.lock_read().failure {
            Some(first) => Err(repeat(first)),
            None => Ok(()),
        }
    }

    /// Ends the session with `e`, and returns `e` or the repeat of an earlier
    /// failure.
    ///
    /// The first failure stays the failure of the session. The call drops the
    /// reader and the writer, and wakes every waiting call.
    ///
    /// The call records the failure before it takes the writer. A call that
    /// checks for a failure under the lock of the write side then cannot give
    /// the writer back to a failed session.
    fn fail(&self, e: Error) -> Error {
        let (out, reader, abandoned, waiting) = {
            let mut read = self.lock_read();
            let out = match &read.failure {
                Some(first) => repeat(first),
                None => {
                    read.failure = Some(repeat(&e));
                    e
                }
            };
            (
                out,
                read.reader.take(),
                read.abandoned.take(),
                std::mem::take(&mut read.waiting),
            )
        };
        let writer = self.lock_write().writer.take();
        drop((reader, abandoned, writer));
        for waker in waiting.into_values() {
            waker.wake();
        }
        out
    }

    /// Takes the reader for the call at `place` when its reply is next.
    async fn wait_turn(&self, place: u64) -> Result<Box<Reader>> {
        poll_fn(|cx| {
            let mut read = self.lock_read();
            if let Some(first) = &read.failure {
                return Poll::Ready(Err(repeat(first)));
            }
            if read.turn == place
                && let Some(reader) = read.reader.take()
            {
                return Poll::Ready(Ok(reader));
            }
            match read.waiting.entry(place) {
                Entry::Occupied(mut stored) => {
                    if !stored.get().will_wake(cx.waker()) {
                        stored.insert(cx.waker().clone());
                    }
                }
                Entry::Vacant(slot) => {
                    slot.insert(cx.waker().clone());
                }
            }
            Poll::Pending
        })
        .await
    }

    /// Gives back the reader after the reply of `place` ended, and wakes the
    /// call whose reply is next.
    fn advance(&self, reader: Box<Reader>, place: u64) {
        let waker = {
            let mut read = self.lock_read();
            if read.failure.is_none() {
                read.reader = Some(reader);
            }
            read.advance(place)
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    }

    /// Gives back the reader for the body of the reply at the turn, which
    /// reads it in place. If the session failed, the call drops the reader
    /// and returns the repeat of the first failure.
    fn lend(&self, reader: Box<Reader>) -> Result<()> {
        let mut read = self.lock_read();
        match &read.failure {
            Some(first) => Err(repeat(first)),
            None => {
                read.reader = Some(reader);
                Ok(())
            }
        }
    }
}

impl ReadSide {
    /// Moves the turn past the reply of `place`, and returns the waker of the
    /// call whose reply is next.
    fn advance(&mut self, place: u64) -> Option<Waker> {
        self.turn = place + 1;
        self.waiting.remove(&(place + 1))
    }
}

/// A call that took its place in the pipeline.
///
/// If it is dropped before the call read the head of its reply, it ends the
/// session. The reply of the call still arrives, and the codec is not
/// cancel-safe.
struct Placed<'a> {
    shared: &'a Shared,
    armed: bool,
}

impl Placed<'_> {
    fn disarm(mut self) {
        self.armed = false;
    }
}

impl Drop for Placed<'_> {
    fn drop(&mut self) {
        if self.armed {
            self.shared.fail(Error::InvalidInput(
                "a call was dropped before its reply".into(),
            ));
        }
    }
}

/// The open of a session over a pair of byte streams, and its calls.
impl StreamSession {
    /// Opens a session over a pair of byte streams.
    ///
    /// `input` carries the bytes from the server, and `output` the bytes to
    /// it. The session sends [`PullHello`] with [`PULL_PROTOCOL_VERSION`] and
    /// reads [`PullHelloReply`](crate::proto::PullHelloReply).
    ///
    /// The caller owns the liveness of the two streams. The session puts no
    /// time limit on a read. A peer that stays silent keeps a call waiting
    /// until the caller drops its future or closes the streams.
    ///
    /// # Errors
    ///
    /// - An `Error` message from the server, as the [`Error`] variant of its
    ///   code.
    /// - [`Error::VersionUnsupported`] if the reply states a version out of
    ///   `1..=PULL_PROTOCOL_VERSION`. The session then closes `output` and
    ///   sends no `Get`.
    /// - [`Error::Protocol`] if the reply is a message of another kind, or if
    ///   the codec refuses a frame of the reply.
    /// - [`Error::Protocol`] if `agent` holds a NUL byte.
    /// - [`Error::LimitExceeded`] if the `PullHello` frame or a frame of the
    ///   reply is longer than [`MIN_FRAME_LIMIT`].
    /// - [`Error::Io`] if a read or a write of a stream fails. If `input`
    ///   ends before the reply, the kind is `UnexpectedEof`.
    ///
    /// If the write of `PullHello` fails with [`Error::Io`], the call then
    /// reads the message that the server can have sent before it closed. If
    /// that message is an `Error` message, the call returns its variant.
    pub async fn over_stream<R, W>(input: R, output: W, opts: StreamSessionOptions) -> Result<Self>
    where
        R: AsyncRead + Unpin + Send + 'static,
        W: AsyncWrite + Unpin + Send + 'static,
    {
        StreamSession::open(Box::new(input), Box::new(output), opts, None).await
    }

    /// Opens a session over `input` and `output`. `pending_limit` is the
    /// longest wait for a pending message after a failed write.
    pub(crate) async fn open(
        input: Input,
        output: Output,
        opts: StreamSessionOptions,
        pending_limit: Option<Duration>,
    ) -> Result<StreamSession> {
        let mut reader = FrameReader::new(BufReader::with_capacity(STREAM_BUFFER, input));
        let mut writer = FrameWriter::new(output);
        let agent = opts
            .agent
            .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
        let hello = Message::PullHello(PullHello {
            version: PULL_PROTOCOL_VERSION,
            agent: Some(agent),
        });
        let written = match writer.write_message(&hello).await {
            Ok(()) => writer.flush().await,
            Err(e) => Err(e),
        };
        if let Err(e) = written {
            drop(writer);
            return Err(match read_pending(&mut reader, pending_limit).await {
                Some(Message::Error(sent)) if matches!(e, Error::Io(_)) => sent.into(),
                _ => e,
            });
        }
        let reply = match reader.read_message().await? {
            Some(Message::PullHelloReply(reply)) => reply,
            Some(Message::Error(e)) => return Err(e.into()),
            Some(other) => {
                return Err(protocol(format!(
                    "{:?} in reply to PullHello",
                    other.kind()
                )));
            }
            None => return Err(eof("the reply to PullHello")),
        };
        if !(1..=PULL_PROTOCOL_VERSION).contains(&reply.version) {
            let _ = writer.into_inner().close().await;
            return Err(Error::VersionUnsupported(format!(
                "the server replied with pull version {}, and the client speaks 1 to \
                 {PULL_PROTOCOL_VERSION}",
                reply.version
            )));
        }
        let outstanding = opts.max_outstanding.unwrap_or(DEFAULT_OUTSTANDING).max(1);
        Ok(StreamSession {
            inner: StreamInner {
                shared: Arc::new(Shared {
                    places: Arc::new(Gate::new(outstanding)),
                    writing: Arc::new(Gate::new(1)),
                    write: Mutex::new(WriteSide {
                        writer: Some(writer.into_inner()),
                        next: 0,
                    }),
                    read: Mutex::new(ReadSide {
                        reader: Some(Box::new(reader)),
                        abandoned: None,
                        turn: 0,
                        waiting: BTreeMap::new(),
                        failure: None,
                    }),
                    pending_limit,
                }),
                max_outstanding: outstanding,
                transport: None,
            },
        })
    }

    /// Attaches the child process whose standard streams the session uses.
    pub(crate) fn with_transport(mut self, child: Transport) -> StreamSession {
        self.inner.transport = Some(Box::new(child));
        self
    }

    /// Returns the number of calls that hold a place in the pipeline at one
    /// time, at least 1.
    pub(crate) fn max_outstanding(&self) -> usize {
        self.inner.max_outstanding
    }

    /// Asks for the file at `path` and waits for the head of its reply.
    ///
    /// `path` is relative to the repository root. The call returns `None` if
    /// the server does not serve the path. The [`PullBody`] holds the body to
    /// `max_len` bytes and to its stated length.
    ///
    /// If [`max_outstanding`](StreamSessionOptions::max_outstanding) calls hold
    /// a place, the call waits. It then takes its place, and writes and
    /// flushes its `Get` frame under one lock.
    ///
    /// The caller must read each body to its end, or drop it, before it
    /// awaits a later `get`. A later call waits for the end of each earlier
    /// body before it reads its own reply. If the future of the call is
    /// dropped after the call took its place, the session ends.
    ///
    /// If the write of the `Get` frame fails, the call waits for the turn of
    /// its reply. It then reads the message that the server can have sent
    /// before it closed. If [`connect`](StreamSession::connect) opened the
    /// session, this read takes the ssh time limits of
    /// [`PushSession::connect`](super::PushSession::connect). If
    /// [`over_stream`](StreamSession::over_stream) opened the session, this
    /// read has no time limit.
    ///
    /// # Errors
    ///
    /// - [`Error::LimitExceeded`] if the `Get` frame of `path` is longer than
    ///   [`MIN_FRAME_LIMIT`]. The session stays usable, and the call writes
    ///   nothing.
    /// - [`Error::Protocol`] if `path` holds a NUL byte. The session stays
    ///   usable, and the call writes nothing.
    /// - The repeat of the first failure, if the session failed before the
    ///   call or while it waits.
    /// - [`Error::LimitExceeded`] if the stated length of the body is more
    ///   than `max_len`. The session ends before it reads the body.
    /// - [`Error::LimitExceeded`] if a frame of the reply is longer than
    ///   [`MIN_FRAME_LIMIT`].
    /// - An `Error` message from the server, as the [`Error`] variant of its
    ///   code.
    /// - [`Error::Protocol`] if the reply is a message of another kind, or if
    ///   the codec refuses a frame of the reply.
    /// - [`Error::Io`] if a read or a write of the stream fails. If the stream
    ///   ends before the reply, the kind is `UnexpectedEof`.
    ///
    /// If the write of the `Get` frame fails and the server sent an `Error`
    /// message before it closed, the call returns the variant of that
    /// message. Otherwise it returns the [`Error::Io`] of the write.
    ///
    /// A failure ends the session, as [Failures](StreamSession#failures)
    /// states.
    pub async fn get(&self, path: &str, max_len: u64) -> Result<Option<PullBody>> {
        self.inner.shared.check()?;
        let get = Message::Get(path.to_owned());
        let frame = encode_frame(&get, MIN_FRAME_LIMIT)?;
        let Message::Get(path) = get else {
            unreachable!("the message is a Get");
        };
        self.request(Kind::Get, frame, path, max_len).await
    }

    /// Asks for the ref listing of `refs` and `collections` and waits for the
    /// head of its reply.
    ///
    /// `refs` selects the local refs. `collections` selects the collection
    /// refs by `ID/NAME`, and `None` asks for no collection ref. The call
    /// sends the entries of the two selectors by the rules of
    /// [Ref patterns](super::PullSession#ref-patterns). The [`PullBody`] holds
    /// the listing to `max_len` bytes and to its stated length.
    ///
    /// The call takes its place in the [pipeline](StreamSession#pipeline) as
    /// [`get`](StreamSession::get) does, and it has the same rules for the
    /// body and for a drop of its future.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if the entries break a limit of
    ///   [Ref patterns](super::PullSession#ref-patterns). The session stays
    ///   usable, and the call writes nothing.
    /// - [`Error::LimitExceeded`] if the `ListRefs` frame is longer than
    ///   [`MIN_FRAME_LIMIT`]. The session stays usable, and the call writes
    ///   nothing.
    /// - [`Error::Protocol`] if the reply is a `GetReply` whose `found` is
    ///   `false`, or that states no length. The session fails.
    /// - Each failure of the session that [`get`](StreamSession::get) lists.
    ///   If the server refuses an entry, the error is [`Error::Protocol`]. If
    ///   the listing is over the cap of the server, the error is
    ///   [`Error::LimitExceeded`].
    ///
    /// A failure ends the session, as [Failures](StreamSession#failures)
    /// states.
    pub async fn list_refs(
        &self,
        refs: &RefSelector,
        collections: Option<&RefSelector>,
        max_len: u64,
    ) -> Result<PullBody> {
        self.inner.shared.check()?;
        let request = wire_entries(refs, collections)?;
        let frame = encode_frame(&Message::ListRefs(request), MIN_FRAME_LIMIT)?;
        let body = self
            .request(Kind::ListRefs, frame, "ListRefs".to_owned(), max_len)
            .await?;
        Ok(body.expect("a ListRefs reply always has a body"))
    }

    /// Writes `frame`, a request of `kind`, in the pipeline and reads the
    /// head of its reply.
    ///
    /// `label` names the request in the errors and in the body. A `GetReply`
    /// whose `found` is `false` gives `None` for a `Get`, and fails the
    /// session for a `ListRefs`. A `GetReply` that states no length also fails
    /// the session for a `ListRefs`.
    async fn request(
        &self,
        kind: Kind,
        frame: Vec<u8>,
        label: String,
        max_len: u64,
    ) -> Result<Option<PullBody>> {
        let shared = &self.inner.shared;
        let place = shared.places.acquire(Priority::Normal).await;
        let turn = shared.writing.acquire(Priority::Normal).await;
        shared.check()?;
        let (seq, writer) = {
            let mut write = shared.lock_write();
            let seq = write.next;
            write.next += 1;
            (seq, write.writer.take())
        };
        let placed = Placed {
            shared,
            armed: true,
        };
        let written = match writer {
            Some(mut writer) => {
                let written = match writer.write_all(&frame).await {
                    Ok(()) => writer.flush().await.map_err(Error::from),
                    Err(e) => Err(e.into()),
                };
                // A failed write drops the writer, so the server reads the end
                // of its input. The check of a failure runs under the lock of
                // the write side: a session that failed during the write keeps
                // no writer.
                if written.is_ok() {
                    let mut write = shared.lock_write();
                    if shared.check().is_ok() {
                        write.writer = Some(writer);
                    }
                }
                written
            }
            // A write failed before this call: the call that failed gives the
            // failure at its turn, and this call repeats it.
            None => Ok(()),
        };
        drop(turn);
        let mut reader = shared.wait_turn(seq).await?;
        if let Err(e) = written {
            let pending = read_pending(&mut reader, shared.pending_limit).await;
            drop(reader);
            placed.disarm();
            return Err(shared.fail(match pending {
                Some(Message::Error(sent)) if matches!(e, Error::Io(_)) => sent.into(),
                _ => e,
            }));
        }
        let reply = reader.read_message().await;
        placed.disarm();
        match reply {
            Ok(Some(Message::GetReply(GetReply { found: false, .. })))
                if kind == Kind::ListRefs =>
            {
                drop(reader);
                Err(shared.fail(protocol("GetReply with found false in reply to ListRefs")))
            }
            Ok(Some(Message::GetReply(GetReply {
                found: true,
                len: None,
            }))) if kind == Kind::ListRefs => {
                drop(reader);
                Err(shared.fail(protocol("GetReply with no length in reply to ListRefs")))
            }
            Ok(Some(Message::GetReply(GetReply { found: false, .. }))) => {
                shared.advance(reader, seq);
                drop(place);
                Ok(None)
            }
            Ok(Some(Message::GetReply(GetReply { found: true, len }))) => {
                if let Some(len) = len
                    && len > max_len
                {
                    drop(reader);
                    return Err(shared.fail(Error::LimitExceeded(format!(
                        "{label}: a body of {len} bytes is over the limit {max_len}"
                    ))));
                }
                shared.lend(reader)?;
                Ok(Some(PullBody {
                    len,
                    inner: Mutex::new(BodyInner {
                        shared: Arc::clone(shared),
                        state: BodyState::Reading,
                        place: Some(place),
                        seq,
                        path: label,
                        len,
                        max_len,
                        read: 0,
                    }),
                }))
            }
            Ok(Some(Message::Error(e))) => Err(shared.fail(e.into())),
            Ok(Some(other)) => {
                Err(shared.fail(protocol(format!("{:?} in reply to {kind:?}", other.kind()))))
            }
            Ok(None) => Err(shared.fail(eof(&format!("the reply to {kind:?}")))),
            Err(e) => Err(shared.fail(e)),
        }
    }

    /// Ends the session.
    ///
    /// An end is clean if the session read the end of every reply. After a
    /// clean end, the session closes its output at a frame boundary. The call
    /// then returns `Ok`, whatever the exit status of the ssh client.
    ///
    /// At any other end, the session closes its output and drops its input
    /// before it waits for the ssh client. Because the session drops the
    /// input first, a server that is blocked in a write of a body does not
    /// keep the client open. The session then fails with the error that the
    /// call returns, and a later read of a held body repeats that error.
    ///
    /// If [`connect`](StreamSession::connect) opened the session, the call then
    /// waits for the ssh client to exit. The wait takes the ssh time limits
    /// of [`PushSession::connect`](super::PushSession::connect).
    ///
    /// # Errors
    ///
    /// - The repeat of the first failure, if the session failed.
    /// - [`Error::InvalidInput`] if the body of a reply is not read to its
    ///   end, for example a body that the caller still holds.
    /// - [`Error::Transport`] with the exit status, if the ssh client exited
    ///   with a failure status and the error of the session is
    ///   [`Error::Io`]. Only a session that [`connect`](StreamSession::connect)
    ///   opened returns it.
    pub async fn finish(mut self) -> Result<()> {
        let transport = self.inner.transport.take();
        let shared = &self.inner.shared;
        let next = shared.lock_write().next;
        let unclean = {
            let read = shared.lock_read();
            match &read.failure {
                Some(first) => Some(repeat(first)),
                None if read.reader.is_none() || read.turn != next => Some(Error::InvalidInput(
                    "the session ended while a body was unread".into(),
                )),
                None => None,
            }
        };
        let result = match unclean {
            // The failure drops the reader and the writer, also while the
            // caller holds a body, whose later read repeats the failure.
            Some(e) => Err(shared.fail(e)),
            None => {
                let writer = shared.lock_write().writer.take();
                if let Some(mut output) = writer {
                    let _ = output.close().await;
                }
                let reader = shared.lock_read().reader.take();
                drop(reader);
                Ok(())
            }
        };
        match transport {
            Some(transport) => transport.finish(result).await,
            None => result,
        }
    }
}

impl Drop for StreamSession {
    fn drop(&mut self) {
        // A body that the caller holds keeps the shared state, so this drop
        // closes the output.
        let writer = self.inner.shared.lock_write().writer.take();
        drop(writer);
    }
}

/// The body of a reply to [`get`](StreamSession::get) or
/// [`list_refs`](StreamSession::list_refs).
///
/// A `PullBody` is an `AsyncRead`. A read gives the bytes of the body until
/// the chunk that ends it, and then end of file. When a read meets that
/// chunk, the session moves to the next reply. The body is `Send + Sync`.
///
/// # Failures
///
/// Each of these events in a read ends the session:
///
/// - a body that is longer than the `max_len` of its call
/// - a body whose stated length is different from the sum of its chunks
/// - an `Error` message after the abandon marker
/// - a failed read
///
/// The read then fails with an `io::Error` that carries the [`Error`] of the
/// session, and each later read fails the same way. If that error is an
/// [`Error::Io`], the `io::Error` has its kind. Otherwise the kind is
/// `Other`.
///
/// The session can also fail for another reason, for example a dropped
/// `get` or `list_refs` future, or [`StreamSession::finish`]. A later read
/// of the body then fails with the first failure and reads no more of the
/// body. A drop of the body before its end also ends the session.
pub struct PullBody {
    len: Option<u64>,
    inner: Mutex<BodyInner>,
}

struct BodyInner {
    shared: Arc<Shared>,
    state: BodyState,
    /// The place of the call, which the end of the body releases.
    place: Option<Permit>,
    seq: u64,
    path: String,
    len: Option<u64>,
    max_len: u64,
    /// The number of bytes of the body that the reads gave so far.
    read: u64,
}

enum BodyState {
    /// The read of the body is in progress. The read side of the session
    /// holds the reader, or the read of the frame that follows the abandon
    /// marker.
    Reading,
    /// The body ended.
    Ended,
    /// The session failed. Each read repeats the error.
    Failed(Error),
}

impl PullBody {
    /// Returns the length that the server stated for the body, if any.
    // A body with no stated length has no answer to `is_empty`.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> Option<u64> {
        self.len
    }
}

impl std::fmt::Debug for PullBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PullBody")
            .field("len", &self.len)
            .finish_non_exhaustive()
    }
}

impl BodyInner {
    /// Ends the session with `e`, and returns the error of the read.
    fn fail(&mut self, e: Error) -> io::Error {
        let e = self.shared.fail(e);
        self.state = BodyState::Failed(repeat(&e));
        self.place = None;
        body_error(e)
    }

    /// Adds `n` bytes to the count of the body, and checks the count against
    /// the cap and the stated length.
    fn count(&mut self, n: usize) -> Result<()> {
        self.read += n as u64;
        if self.read > self.max_len {
            return Err(Error::LimitExceeded(format!(
                "{}: the body passed the limit of {} bytes",
                self.path, self.max_len
            )));
        }
        if let Some(len) = self.len
            && self.read > len
        {
            return Err(protocol(format!(
                "{}: the body holds more than its stated length of {len} bytes",
                self.path
            )));
        }
        Ok(())
    }

    fn poll_read(&mut self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>> {
        match &self.state {
            BodyState::Ended => return Poll::Ready(Ok(0)),
            BodyState::Failed(e) => return Poll::Ready(Err(body_error(repeat(e)))),
            BodyState::Reading => {}
        }
        let mut next = None;
        // The bytes read, or 0 at the end of the body.
        let got = {
            let mut guard = self.shared.lock_read();
            let read = &mut *guard;
            loop {
                if let Some(first) = &read.failure {
                    break Err(repeat(first));
                }
                if let Some(abandoned) = read.abandoned.as_mut() {
                    let frame = ready!(abandoned.as_mut().poll(cx));
                    read.abandoned = None;
                    break Err(match frame {
                        Ok(Some(Message::Error(sent))) => sent.into(),
                        Ok(Some(other)) => {
                            protocol(format!("{:?} after the abandon marker", other.kind()))
                        }
                        Ok(None) => eof("the Error after the abandon marker"),
                        Err(e) => e,
                    });
                }
                let Some(reader) = read.reader.as_mut() else {
                    unreachable!("the body holds the turn of the reader");
                };
                if buf.is_empty() {
                    return Poll::Ready(Ok(0));
                }
                match ready!(reader.poll_step(cx, buf)) {
                    Ok(Step::Data(n)) => break Ok(n),
                    Ok(Step::End) => {
                        if let Some(len) = self.len
                            && len != self.read
                        {
                            break Err(protocol(format!(
                                "{}: the body holds {} bytes, not its stated length of {len}",
                                self.path, self.read
                            )));
                        }
                        next = read.advance(self.seq);
                        break Ok(0);
                    }
                    Ok(Step::Marker(_)) => {
                        if let Some(mut reader) = read.reader.take() {
                            read.abandoned =
                                Some(Box::pin(async move { reader.read_message().await }));
                        }
                    }
                    Err(e) => break Err(e),
                }
            }
        };
        match got {
            Ok(0) => {
                self.state = BodyState::Ended;
                self.place = None;
                if let Some(waker) = next {
                    waker.wake();
                }
                Poll::Ready(Ok(0))
            }
            Ok(n) => Poll::Ready(match self.count(n) {
                Ok(()) => Ok(n),
                Err(e) => Err(self.fail(e)),
            }),
            Err(e) => Poll::Ready(Err(self.fail(e))),
        }
    }
}

impl AsyncRead for PullBody {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        self.get_mut()
            .inner
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner)
            .poll_read(cx, buf)
    }
}

impl Drop for PullBody {
    fn drop(&mut self) {
        let inner = self.inner.get_mut().unwrap_or_else(PoisonError::into_inner);
        if matches!(inner.state, BodyState::Reading) {
            inner.shared.fail(Error::InvalidInput(
                "a pull body was dropped before its end".into(),
            ));
        }
    }
}

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

    fn selector(entries: &[&str]) -> RefSelector {
        RefSelector::parse(entries.iter().copied()).unwrap()
    }

    fn wire(entries: &[&str]) -> Vec<String> {
        wire_entries(&selector(entries), None).unwrap().refs
    }

    /// `wire_entries` removes an exact duplicate of one kind and keeps the
    /// first appearance. An entry that another entry covers stays.
    #[test]
    fn exact_duplicates_are_removed_in_order() {
        assert_eq!(wire(&["x", "a", "x", "b", "a"]), ["x", "a", "b"]);
        assert_eq!(wire(&["a", "a/b", "a"]), ["a", "a/b"]);
        assert!(wire(&[]).is_empty());
        assert_eq!(wire(&["main"; 300]), ["main"]);
    }

    /// The positive entries come first, then the negative entries with their
    /// `!`. A positive and a negative entry of the same text both stay.
    #[test]
    fn negative_entries_follow_positive_entries() {
        assert_eq!(
            wire(&["!x", "a/**", "!a/b/*", "x", "!x", "a/*"]),
            ["a/**", "x", "a/*", "!x", "!a/b/*"]
        );
    }

    /// The limit counts positive and negative entries together.
    #[test]
    fn the_limit_counts_both_kinds() {
        let entries: Vec<String> = (0..=MAX_REF_PATTERNS)
            .map(|n| {
                if n % 2 == 0 {
                    format!("r{n}")
                } else {
                    format!("!r{n}")
                }
            })
            .collect();
        let entries: Vec<&str> = entries.iter().map(String::as_str).collect();
        let err = wire_entries(&selector(&entries), None).unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
        assert_eq!(wire(&entries[1..]).len(), MAX_REF_PATTERNS);
    }

    /// The two lists share the limit. An entry repeated within one list is
    /// sent one time, and the same entry in the two lists is sent in each
    /// list. An absent list and an empty list stay apart.
    #[test]
    fn the_two_lists_share_the_limit() {
        let names: Vec<String> = (0..MAX_REF_PATTERNS).map(|n| format!("r{n}")).collect();
        let names: Vec<&str> = names.iter().map(String::as_str).collect();
        let (half, rest) = names.split_at(MAX_REF_PATTERNS / 2);
        let request = wire_entries(&selector(half), Some(&selector(rest))).unwrap();
        assert_eq!(request.refs.len() + request.collections.unwrap().len(), 256);
        let err = wire_entries(&selector(half), Some(&selector(&names[..129]))).unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
        let err = wire_entries(&selector(&names), Some(&selector(&["x/*"]))).unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");

        let request =
            wire_entries(&selector(&["a", "a"]), Some(&selector(&["a", "!b", "a"]))).unwrap();
        assert_eq!(request.refs, ["a"]);
        assert_eq!(request.collections.unwrap(), ["a", "!b"]);
        assert_eq!(
            wire_entries(&selector(&[]), None).unwrap().collections,
            None
        );
        assert_eq!(
            wire_entries(&selector(&[]), Some(&selector(&[])))
                .unwrap()
                .collections,
            Some(Vec::new())
        );
        let full = wire_entries(&selector(&names), Some(&selector(&[]))).unwrap();
        assert_eq!(full.refs.len(), MAX_REF_PATTERNS);
    }

    /// `wire_entries` refuses an entry over the limit of bytes or parts, and
    /// accepts an entry at the limit. The `!` counts as one byte and adds no
    /// part. The limits apply to an entry of each list.
    #[test]
    fn an_entry_over_a_limit_is_refused() {
        let parts = |n: usize| vec!["a"; n].join("/");
        let long = |n: usize| "a".repeat(n);
        for ok in [
            parts(MAX_REF_ENTRY_PARTS),
            long(MAX_REF_ENTRY_LEN),
            format!("!{}", long(MAX_REF_ENTRY_LEN - 1)),
            format!("!{}", parts(MAX_REF_ENTRY_PARTS)),
        ] {
            assert_eq!(wire(&[&ok]), [ok]);
        }
        for bad in [
            parts(MAX_REF_ENTRY_PARTS + 1),
            long(MAX_REF_ENTRY_LEN + 1),
            format!("!{}", long(MAX_REF_ENTRY_LEN)),
            format!("!{}", parts(MAX_REF_ENTRY_PARTS + 1)),
        ] {
            let err = wire_entries(&selector(&[&bad]), None).unwrap_err();
            assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
            let err = wire_entries(&selector(&[]), Some(&selector(&[&bad]))).unwrap_err();
            assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
        }
    }
}