ostrya-remote 0.5.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
//! The client sessions of the push and of the pull, and the one-way stream.
//!
//! A [`PushSession`] opens with `Hello` and gives the facts of the server as
//! [`ServerInfo`]. Its calls are:
//!
//! - [`missing`](PushSession::missing) asks the server which objects it needs.
//! - [`send`](PushSession::send) sends them from an [`ObjectSource`], with the
//!   detached metadata of their commits.
//! - [`commit`](PushSession::commit) asks the server to update its refs in
//!   one transaction.
//! - [`server_commit`](PushSession::server_commit) asks the server to make a
//!   commit over a tree that it holds, and to move a branch to it.
//!
//! [`PushProgress`] counts the progress of a session, and [`PushOutcome`]
//! gives the result of a session that committed.
//!
//! A [`StreamSession`] reads files and ref listings of a server repository,
//! and gives each body as a [`PullBody`]. A [`PullSession`] reads the summary
//! and the ref listings of a remote over HTTP or over a stream session.
//!
//! [`export_stream`] writes a one-way stream: the messages of a push session in
//! one direction, for a receiver that sends no reply.

pub(crate) mod http;
mod one_way;
mod progress;
mod pull;
mod pull_session;
pub(crate) mod stream;
mod writer;

use std::collections::HashSet;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use futures_io::{AsyncRead, AsyncWrite};
use ostrya_core::{Checksum, FileHeader, ObjectName, ObjectType};
use ostrya_gvariant::Value;

pub use one_way::export_stream;
pub use progress::{PushPhase, PushProgress, PushProgressFn, PushProgressSnapshot, PushStats};
pub use pull::{PullBody, StreamSession, StreamSessionOptions};
pub use pull_session::PullSession;

use self::http::{Endpoint, HttpLink};
use self::progress::Counters;
use self::stream::Stream;
use self::writer::{MetaClaims, Upload};
use crate::error::{Error, Result};
use crate::proto::{
    CommitRequest, Encoding, Hello, HelloReply, Message, PROTOCOL_VERSION, RefOutcome, RefState,
    RefUpdate, ServerCommit, check_server_commit_metadata, have_entries_within, have_type,
    protocol, server_commit_frame_len, server_commit_reply_frame_len,
};
use crate::transport::Transport;

/// A boxed `Send` future, the return type of the [`ObjectSource`] methods.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// The encoding of the content objects that a session sends.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Compression {
    /// The `raw` encoding: the framed file header and the payload.
    #[default]
    None,
    /// The `deflate` encoding at `level`, 1 through 9.
    ///
    /// The session uses it if the server lists `deflate`. If the server lists
    /// `raw` alone, the session sends `raw`.
    Deflate {
        /// The compression level, 1 through 9.
        level: u8,
    },
}

/// A stream of object bytes that a source gives to the session.
pub trait ObjectReader: AsyncRead + Send + Sync + Unpin {}

impl<T: AsyncRead + Send + Sync + Unpin + ?Sized> ObjectReader for T {}

/// The data of one object, as an [`ObjectSource`] gives it.
pub enum ObjectData {
    /// A content object that the session encodes.
    ///
    /// `header` is the file header of the object, and `size` is the length of
    /// its payload. A regular file has a `payload`. A symlink has no `payload`
    /// and a `size` of 0.
    ///
    /// For `raw`, the session sends the framed header and the payload. For
    /// `deflate`, it sends the framed archive header, and then the payload
    /// through its own raw-DEFLATE compressor.
    Content {
        /// The file header.
        header: FileHeader,
        /// The length of the payload, in bytes.
        size: u64,
        /// The payload of a regular file.
        payload: Option<Box<dyn ObjectReader>>,
    },
    /// The object bytes in `encoding`, which the session copies as they are.
    ///
    /// A metadata object is `raw` alone. The session sends a content object in
    /// `raw` as `raw`, also if it deflates. Bytes in `deflate` for a metadata
    /// object, or for a server that does not list `deflate`, are
    /// [`Error::InvalidInput`].
    Encoded {
        /// The encoding of the bytes.
        encoding: Encoding,
        /// The bytes.
        reader: Box<dyn ObjectReader>,
    },
}

impl fmt::Debug for ObjectData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ObjectData::Content {
                header,
                size,
                payload,
            } => f
                .debug_struct("Content")
                .field("header", header)
                .field("size", size)
                .field("payload", &payload.is_some())
                .finish(),
            ObjectData::Encoded { encoding, .. } => f
                .debug_struct("Encoded")
                .field("encoding", encoding)
                .finish_non_exhaustive(),
        }
    }
}

/// The detached metadata of a commit, as an [`ObjectSource`] gives it.
///
/// [`ObjectSource::detached_metadata_encoded`] returns it. The session
/// serializes a [`Dict`](DetachedMetadata::Dict) on the blocking pool of
/// `ostrya-rt`. Under the `tokio` backend, this pool is the blocking pool of
/// the tokio runtime, so the serialization panics outside a tokio runtime
/// context.
///
/// If a dict does not serialize as `a{sv}`, the object stream stops with
/// [`Error::InvalidInput`]. If the bytes of either form are more than 128 MiB
/// ([`MAX_METADATA_SIZE`](ostrya_core::MAX_METADATA_SIZE)), the object stream
/// also stops with [`Error::InvalidInput`]. An ostrya server refuses bytes
/// that are not a normal-form `a{sv}` dict with the code `protocol`.
pub enum DetachedMetadata {
    /// An `a{sv}` dict, which the session serializes.
    Dict(Value),
    /// The bytes of an `a{sv}` dict in normal form.
    ///
    /// The session sends the bytes as they are, and checks only their length.
    Encoded(Vec<u8>),
}

/// A source of the objects that a session sends.
pub trait ObjectSource: Send + Sync {
    /// Returns the name of each object that `commit` reaches, and of the commit.
    ///
    /// No session method calls `objects`. A caller gives the list to
    /// [`missing`](PushSession::missing) to find the objects to
    /// [`send`](PushSession::send).
    ///
    /// # Errors
    ///
    /// The error depends on the implementation:
    ///
    /// - [`TreeModel`](crate::tree::TreeModel) returns [`Error::InvalidInput`],
    ///   because the model holds no commit.
    /// - The repository source of the `ostrya` crate returns
    ///   [`Error::Source`] if the walk of `commit` in the repository fails.
    fn objects<'a>(&'a self, commit: &'a Checksum) -> BoxFuture<'a, Result<Vec<ObjectName>>>;

    /// Returns the data of the object `name`.
    ///
    /// `encoding` is the encoding in which the session sends the object:
    /// `deflate` for a content object if the session deflates, and `raw` for
    /// all other objects. A source that holds the object in that encoding can
    /// give its bytes as [`ObjectData::Encoded`].
    ///
    /// # Errors
    ///
    /// An error of the source stops the object stream.
    /// [`send`](PushSession::send) and [`export_stream`] return it as
    /// [`Error::Source`].
    fn open<'a>(
        &'a self,
        name: &'a ObjectName,
        encoding: Encoding,
    ) -> BoxFuture<'a, Result<ObjectData>>;

    /// Returns the detached metadata for `commit`, an `a{sv}` dict.
    ///
    /// The source applies its own filter first. For `None`, the session sends
    /// no detached metadata for `commit`. [`DetachedMetadata`] gives the
    /// checks of the dict.
    ///
    /// The session calls this method only through the default implementation
    /// of
    /// [`detached_metadata_encoded`](ObjectSource::detached_metadata_encoded).
    /// A source that overrides that method must still implement this one.
    ///
    /// # Errors
    ///
    /// An error of the source stops the object stream.
    /// [`send`](PushSession::send) and [`export_stream`] return it as
    /// [`Error::Source`].
    fn detached_metadata<'a>(
        &'a self,
        commit: &'a Checksum,
    ) -> BoxFuture<'a, Result<Option<Value>>>;

    /// Returns the detached metadata for `commit`, as a dict or as its bytes.
    ///
    /// The session sends the detached metadata of each commit through this
    /// method. The default implementation calls
    /// [`detached_metadata`](ObjectSource::detached_metadata) and gives its
    /// dict as [`DetachedMetadata::Dict`]. A source that holds the bytes of
    /// the dict can give them as [`DetachedMetadata::Encoded`].
    ///
    /// For `None`, the session sends no detached metadata for `commit`.
    /// [`DetachedMetadata`] gives the checks of each form.
    ///
    /// # Errors
    ///
    /// An error of the source stops the object stream.
    /// [`send`](PushSession::send) and [`export_stream`] return it as
    /// [`Error::Source`].
    fn detached_metadata_encoded<'a>(
        &'a self,
        commit: &'a Checksum,
    ) -> BoxFuture<'a, Result<Option<DetachedMetadata>>> {
        Box::pin(async move {
            Ok(self
                .detached_metadata(commit)
                .await?
                .map(DetachedMetadata::Dict))
        })
    }

    /// Returns the content bytes of the file objects of `names` in `encoding`.
    ///
    /// `None` means that the source does not know the number. The names that
    /// are not file objects count no byte. The default implementation returns
    /// `None`.
    ///
    /// The content bytes of one file object are the bytes that the session
    /// reads from the reader that [`open`](ObjectSource::open) gives for it
    /// with the same `encoding`:
    ///
    /// - the payload of [`ObjectData::Content`]
    /// - 0 for a symlink
    /// - the bytes of [`ObjectData::Encoded`]
    ///
    /// If the session has a [`PushProgress`] and `names` holds at least one
    /// file object, each [`send`](PushSession::send) call and each
    /// [`export_stream`] call asks once, before the first object. The call
    /// adds the answer to [`bytes_total`](PushProgressSnapshot::bytes_total).
    ///
    /// The method must not read the content of an object. It reads what the
    /// source already holds, or the metadata of each object.
    ///
    /// # Errors
    ///
    /// The session treats an error as `None`. The call adds nothing to the
    /// total and sends the objects.
    fn content_size<'a>(
        &'a self,
        names: &'a [ObjectName],
        encoding: Encoding,
    ) -> BoxFuture<'a, Result<Option<u64>>> {
        let _ = (names, encoding);
        Box::pin(async { Ok(None) })
    }
}

/// The facts of the server, from its `HelloReply`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerInfo {
    /// The protocol version of the session.
    pub version: u32,
    /// The repository mode.
    pub mode: String,
    /// The collection id of the repository.
    pub collection_id: Option<String>,
    /// The collection of the namespace of the session, from the key
    /// `collection` of `HelloReply`.
    ///
    /// `None` is the local refs of the server. The session checks the value
    /// against [`SessionOptions::collection`] when it opens. With no
    /// requested collection, the value is `None`. With a requested id, the
    /// value is that id, or `None` if the id is
    /// [`collection_id`](ServerInfo::collection_id).
    pub collection: Option<String>,
    /// The frame and chunk limit that the session writes with.
    ///
    /// The value is in
    /// [`MIN_FRAME_LIMIT`](crate::proto::MIN_FRAME_LIMIT)`..=`[`MAX_FRAME_LIMIT`](crate::proto::MAX_FRAME_LIMIT).
    pub max_frame: u32,
    /// The highest number of object names in one `Have`.
    pub max_have: u32,
    /// The content encodings that the server accepts.
    pub encodings: Vec<Encoding>,
    /// The most object streams that the server serves at the same time.
    pub parallel_uploads: u32,
    /// The state of each ref that the session named, in the order of the names.
    pub refs: Vec<RefState>,
}

impl ServerInfo {
    /// Returns the collection id that a commit of the session binds to.
    ///
    /// The value is [`collection`](ServerInfo::collection) for a collection
    /// namespace, and [`collection_id`](ServerInfo::collection_id) for the
    /// local refs. `None` is the local refs of a server with no collection
    /// id.
    pub fn binding_collection(&self) -> Option<&str> {
        self.collection.as_deref().or(self.collection_id.as_deref())
    }

    /// Returns the current commit of the ref `name` on the server.
    ///
    /// Returns `None` if the ref is absent, or if the session did not name it.
    pub fn tip(&self, name: &str) -> Option<Checksum> {
        self.refs
            .iter()
            .find(|r| r.name == name)
            .and_then(|r| r.commit)
    }
}

/// The options of a session.
#[derive(Debug, Clone, Default)]
pub struct SessionOptions {
    /// The `agent` that the session sends in `Hello`.
    ///
    /// The default is `ostrya/<version>`.
    pub agent: Option<String>,
    /// The collection id that the session sends in `Hello`, under the key
    /// `collection`.
    ///
    /// `None` targets the local refs of the server. The collection id of the
    /// server also targets its local refs. The session does not check the
    /// id: the server refuses an id that fails the collection-id rule.
    pub collection: Option<String>,
    /// A handle that the session also counts its progress into.
    pub progress: Option<PushProgress>,
}

/// The result of a push that committed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PushOutcome {
    /// The commit that the server made for
    /// [`server_commit`](PushSession::server_commit).
    ///
    /// A session that ends with [`commit`](PushSession::commit) gives
    /// `None`.
    pub commit: Option<Checksum>,
    /// One outcome for each ref update, in the order of the updates.
    pub refs: Vec<RefOutcome>,
    /// The statistics of the session.
    pub stats: PushStats,
}

/// A client session of a push, over a stream transport or over HTTP.
///
/// [`connect`](PushSession::connect) opens a session over ssh or HTTP, and
/// [`prepare`](PushSession::prepare) checks the transport before the open.
/// [`over_stream`](PushSession::over_stream) opens a session over a pair of
/// byte streams.
///
/// If the caller drops a session without [`commit`](PushSession::commit),
/// [`server_commit`](PushSession::server_commit), or
/// [`abort`](PushSession::abort), the session sends nothing more. A stream
/// transport then closes its output, so the server reads the end of the
/// stream. Over HTTP, the server ends the session when its idle timeout ends.
///
/// After the server ends a session over HTTP, it answers each later request
/// of that session with 404. The session reports a 404 on
/// [`missing`](PushSession::missing) or [`send`](PushSession::send) as
/// [`Error::Transport`], and a 404 on [`commit`](PushSession::commit) or
/// [`server_commit`](PushSession::server_commit) as
/// [`Error::CommitOutcomeUnknown`].
///
/// # Verification
///
/// The session does not verify the objects that it sends. It computes no
/// checksum and checks no size. The server verifies each object when it
/// arrives. If a source fails while the session sends an object, the session
/// abandons the object with the abandon marker and ends the session with
/// `Abort`.
///
/// # Concurrent calls
///
/// The session is `Send + Sync`. On a stream transport, the session runs one
/// call at a time. A call to [`missing`](PushSession::missing) or
/// [`send`](PushSession::send) while another call runs fails at once with
/// [`Error::InvalidInput`].
///
/// Over HTTP, several [`send`](PushSession::send) calls can run at the same
/// time, and a [`missing`](PushSession::missing) call can run beside them. A
/// second `missing` call while one runs fails at once with
/// [`Error::InvalidInput`].
///
/// On both transports, a call that fails, or whose future the caller drops
/// before it completes, leaves the session broken. Each later call then fails
/// with [`Error::InvalidInput`]. If `missing` or `send` refuses an argument,
/// the call sends nothing and the session stays usable.
pub struct PushSession {
    inner: SessionInner,
}

struct SessionInner {
    server: ServerInfo,
    counters: Arc<Counters>,
    /// The claims of the detached metadata the session sends.
    claims: MetaClaims,
    link: Link,
}

/// The transport of a session.
enum Link {
    /// A pair of byte streams.
    Stream {
        slot: Mutex<Slot>,
        /// The child process the streams belong to, for a session that
        /// [`PushSession::connect`] opened.
        transport: Option<Transport>,
    },
    /// The receive endpoint of an HTTP server.
    Http(HttpLink),
}

enum Slot {
    /// No call runs.
    Idle(Box<Stream>),
    /// A call runs and holds the stream.
    Busy,
    /// A call failed or was dropped. The stream is gone.
    Poisoned,
}

/// The stream a call holds. The call gives it back with
/// [`release`](Taken::release) when it completes. Dropped without a release,
/// it leaves the session broken.
struct Taken<'a> {
    slot: &'a Mutex<Slot>,
    stream: Option<Box<Stream>>,
}

impl Taken<'_> {
    fn stream(&mut self) -> &mut Stream {
        self.stream.as_mut().expect("the stream is held")
    }

    fn release(mut self) {
        let stream = self.stream.take().expect("the stream is held");
        *self.slot.lock().unwrap_or_else(PoisonError::into_inner) = Slot::Idle(stream);
    }
}

impl Drop for Taken<'_> {
    fn drop(&mut self) {
        if self.stream.is_some() {
            *self.slot.lock().unwrap_or_else(PoisonError::into_inner) = Slot::Poisoned;
        }
    }
}

pub(crate) fn invalid(msg: impl Into<String>) -> Error {
    Error::InvalidInput(msg.into())
}

pub(super) fn broken() -> Error {
    invalid("the session is broken")
}

pub(super) fn unexpected(msg: &Message, request: &str) -> Error {
    protocol(format!("{:?} in reply to {request}", msg.kind()))
}

/// The DEFLATE level of `compression`, or `None` for `raw`. A level outside 1
/// through 9 is [`Error::InvalidInput`].
pub(crate) fn deflate_level(compression: Compression) -> Result<Option<u8>> {
    match compression {
        Compression::None => Ok(None),
        Compression::Deflate { level } if (1..=9).contains(&level) => Ok(Some(level)),
        Compression::Deflate { level } => Err(invalid(format!(
            "compression level {level} is not in 1 through 9"
        ))),
    }
}

/// Asks `source` for the content bytes of the file objects of `names`, sent
/// at `level`, and adds them to the byte total of `counters`. A session with
/// no caller's handle, and names with no file object, ask nothing. An
/// unknown size and a failure add nothing.
async fn count_content_total(
    counters: &Counters,
    source: &dyn ObjectSource,
    names: &[ObjectName],
    level: Option<u8>,
) {
    if !counters.has_caller() || !names.iter().any(|n| n.ty == ObjectType::File) {
        return;
    }
    let encoding = match level {
        Some(_) => Encoding::Deflate,
        None => Encoding::Raw,
    };
    if let Ok(Some(total)) = source.content_size(names, encoding).await {
        counters.content_total(total);
    }
}

/// Refuses a name of a type that `Have` and the objects of a source cannot
/// carry. The session sends detached metadata for a commit on its own.
fn refuse_off_wire(names: &[ObjectName]) -> Result<()> {
    match names.iter().find(|n| !have_type(n.ty)) {
        Some(n) => Err(invalid(format!(
            "object {} of type {:?} is not an object to offer or send",
            n.checksum, n.ty
        ))),
        None => Ok(()),
    }
}

/// Takes the stream of `slot` for one call.
fn take(slot: &Mutex<Slot>) -> Result<Taken<'_>> {
    let mut held = slot.lock().unwrap_or_else(PoisonError::into_inner);
    match std::mem::replace(&mut *held, Slot::Busy) {
        Slot::Idle(stream) => Ok(Taken {
            slot,
            stream: Some(stream),
        }),
        Slot::Busy => Err(invalid("a call is in progress")),
        Slot::Poisoned => {
            *held = Slot::Poisoned;
            Err(broken())
        }
    }
}

/// The stream of an idle session.
fn into_stream(slot: Mutex<Slot>) -> Result<Box<Stream>> {
    match slot.into_inner().unwrap_or_else(PoisonError::into_inner) {
        Slot::Idle(stream) => Ok(stream),
        Slot::Busy | Slot::Poisoned => Err(broken()),
    }
}

/// The facts of the server from `reply`, the reply to a `Hello` with `refs`
/// and `collection`.
///
/// These replies are [`Error::Protocol`]:
///
/// - a version that is not the version of the session;
/// - refs that are not `refs` in order;
/// - a `collection` that does not match the request. A request with no
///   collection needs a reply with none. A request of an id needs a reply of
///   that id, or a reply with none from a server whose collection id is that
///   id.
fn server_info(reply: HelloReply, refs: &[String], collection: Option<&str>) -> Result<ServerInfo> {
    if reply.version != PROTOCOL_VERSION {
        return Err(protocol(format!(
            "the server replied with protocol version {}, not {PROTOCOL_VERSION}",
            reply.version
        )));
    }
    if reply.refs.len() != refs.len() || reply.refs.iter().zip(refs).any(|(s, n)| s.name != *n) {
        return Err(protocol("the refs of HelloReply are not the refs of Hello"));
    }
    let matches = match (collection, reply.collection.as_deref()) {
        (None, None) => true,
        (Some(asked), Some(got)) => asked == got,
        (Some(asked), None) => reply.collection_id.as_deref() == Some(asked),
        (None, Some(_)) => false,
    };
    if !matches {
        let text = |c: Option<&str>| c.map_or_else(|| "none".to_owned(), |id| format!("'{id}'"));
        return Err(protocol(format!(
            "the collection {} of HelloReply does not match the collection {} of Hello",
            text(reply.collection.as_deref()),
            text(collection)
        )));
    }
    Ok(ServerInfo {
        version: reply.version,
        mode: reply.mode,
        collection_id: reply.collection_id,
        collection: reply.collection,
        max_frame: reply.max_frame,
        max_have: reply.max_have,
        encodings: reply.encodings,
        parallel_uploads: reply.parallel_uploads,
        refs: reply.refs,
    })
}

/// The open of a session over a pair of byte streams, and its calls.
impl PushSession {
    /// Opens a session over a pair of byte streams.
    ///
    /// `input` comes from the server, and `output` goes to the server. The
    /// session sends `Hello` with `refs`, the refs that it intends to update,
    /// and reads `HelloReply`.
    ///
    /// 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.
    ///
    /// A session over a stream uses the `futures-io` traits for its I/O, and
    /// needs no async runtime, except for [`send`](PushSession::send) under
    /// the `tokio` backend.
    ///
    /// # Errors
    ///
    /// - An `Error` message from the server, as the [`Error`] variant of its
    ///   code, for example [`Error::VersionUnsupported`].
    /// - [`Error::Protocol`] if the version of `HelloReply` is not the version
    ///   of the session, or if its refs are not the refs of `Hello` in order.
    /// - [`Error::Protocol`] if the `collection` of `HelloReply` does not
    ///   match [`SessionOptions::collection`]. [`ServerInfo::collection`]
    ///   states the match.
    /// - [`Error::Protocol`] for a malformed frame, or for a reply that is not
    ///   `HelloReply`.
    /// - [`Error::LimitExceeded`] for a frame over the frame limit.
    /// - [`Error::Io`] for a failure of a stream. An end of `input` before
    ///   the reply has the kind `UnexpectedEof`.
    pub async fn over_stream<R, W>(
        input: R,
        output: W,
        refs: &[String],
        opts: SessionOptions,
    ) -> Result<PushSession>
    where
        R: AsyncRead + Unpin + Send + 'static,
        W: AsyncWrite + Unpin + Send + 'static,
    {
        PushSession::open(Box::new(input), Box::new(output), refs, opts, None).await
    }

    /// Opens a session over `input` and `output`. `pending_limit` bounds the
    /// wait for a pending message after a failed write.
    pub(crate) async fn open(
        input: stream::Input,
        output: stream::Output,
        refs: &[String],
        opts: SessionOptions,
        pending_limit: Option<Duration>,
    ) -> Result<PushSession> {
        let counters = Arc::new(Counters::new(opts.progress.as_ref()));
        counters.phase(PushPhase::Connecting);
        let mut stream = Stream::new(input, output, Arc::clone(&counters));
        if let Some(limit) = pending_limit {
            stream.set_pending_limit(limit);
        }
        let agent = opts
            .agent
            .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
        stream
            .request(&Message::Hello(Hello {
                version: PROTOCOL_VERSION,
                agent: Some(agent),
                refs: refs.to_vec(),
                collection: opts.collection.clone(),
                one_way: false,
            }))
            .await?;
        let reply = match stream.next().await? {
            Message::HelloReply(reply) => reply,
            Message::Error(e) => return Err(e.into()),
            other => return Err(unexpected(&other, "Hello")),
        };
        let server = server_info(reply, refs, opts.collection.as_deref())?;
        stream.set_write_limit(server.max_frame);
        Ok(PushSession {
            inner: SessionInner {
                server,
                counters,
                claims: MetaClaims::default(),
                link: Link::Stream {
                    slot: Mutex::new(Slot::Idle(Box::new(stream))),
                    transport: None,
                },
            },
        })
    }

    /// Opens a session over HTTP at `endpoint`: sends `Hello` with `refs` and
    /// reads `HelloReply`.
    pub(crate) async fn open_http(
        endpoint: Endpoint,
        refs: &[String],
        opts: SessionOptions,
    ) -> Result<PushSession> {
        let counters = Arc::new(Counters::new(opts.progress.as_ref()));
        counters.phase(PushPhase::Connecting);
        let agent = opts
            .agent
            .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
        let (server, link) = http::open(endpoint, refs, agent, opts.collection, &counters).await?;
        Ok(PushSession {
            inner: SessionInner {
                server,
                counters,
                claims: MetaClaims::default(),
                link: Link::Http(link),
            },
        })
    }

    /// Attaches the child process the streams of the session belong to.
    pub(crate) fn with_transport(mut self, child: Transport) -> PushSession {
        if let Link::Stream { transport, .. } = &mut self.inner.link {
            *transport = Some(child);
        }
        self
    }

    /// Returns the facts of the server.
    pub fn server(&self) -> &ServerInfo {
        &self.inner.server
    }

    /// Returns the objects of `names` that the server does not hold.
    ///
    /// The order of the result is the order of `names`. The session sends
    /// `Have` messages of at most `max-have` names each. A `Have` also holds
    /// no more names than its frame can hold within `max-frame`.
    ///
    /// Over HTTP, each `Have` is one request. The session sends the next
    /// `Have` after the response to the one before it.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if the type of a name is not a file, a
    ///   dirtree, a dirmeta, a commit, or a composefs image. The call sends
    ///   nothing, and the session stays usable.
    /// - [`Error::InvalidInput`] if another call runs, as the rules of
    ///   [concurrent calls](PushSession#concurrent-calls) state, or if the
    ///   session is broken.
    /// - An `Error` message from the server, as the [`Error`] variant of its
    ///   code.
    /// - [`Error::Protocol`] for a malformed reply, for a reply that is not
    ///   `HaveReply`, or for a `HaveReply` whose length does not match its
    ///   `Have`.
    /// - [`Error::LimitExceeded`] on a stream transport, for a frame over the
    ///   frame limit.
    /// - [`Error::Io`] for a failure of the stream, or for a failed read of a
    ///   response body over HTTP.
    /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
    /// - [`Error::Transport`] over HTTP, for a status other than 200, 401,
    ///   403, 409, 422, 500, and 503, or for a body that is not one frame. A
    ///   404 for a session that the server ended is such a status.
    pub async fn missing(&self, names: &[ObjectName]) -> Result<Vec<ObjectName>> {
        refuse_off_wire(names)?;
        let slot = match &self.inner.link {
            Link::Stream { slot, .. } => slot,
            Link::Http(link) => {
                return link
                    .missing(&self.inner.server, &self.inner.counters, names)
                    .await;
            }
        };
        let mut taken = take(slot)?;
        let counters = &self.inner.counters;
        counters.phase(PushPhase::Negotiating);
        counters.offered(names);
        let stream = taken.stream();
        let mut missing = Vec::new();
        let server = &self.inner.server;
        let batch_len = server
            .max_have
            .min(have_entries_within(server.max_frame))
            .max(1);
        for batch in names.chunks(batch_len as usize) {
            stream.request(&Message::Have(batch.to_vec())).await?;
            match stream.next().await? {
                Message::HaveReply(reply) => {
                    reply.check_len(batch.len())?;
                    missing.extend(
                        batch
                            .iter()
                            .enumerate()
                            .filter(|(i, _)| reply.is_missing(*i))
                            .map(|(_, n)| *n),
                    );
                }
                Message::Error(e) => return Err(e.into()),
                other => return Err(unexpected(&other, "Have")),
            }
        }
        counters.needed(&missing);
        taken.release();
        Ok(missing)
    }

    /// Sends the objects `names` from `source`, then the detached metadata of
    /// `commits`.
    ///
    /// On a stream transport, the objects go in one object stream. The call
    /// sends the detached metadata of each commit in `commits` that has
    /// detached metadata, if the session did not send it before. `commits`
    /// holds the commits of `names` and the new value of each ref update, also
    /// if `names` does not hold that commit. A call with nothing to send
    /// writes nothing.
    ///
    /// If the session has a [`PushProgress`] and `names` holds at least one
    /// file object, the call first asks [`ObjectSource::content_size`]. The
    /// answer is the number of content bytes that the call sends.
    ///
    /// # HTTP
    ///
    /// Over HTTP, the call sends the objects in at most `parallel-uploads`
    /// object streams at the same time, and in no more streams than the
    /// objects that it sends. Each object stream is one request, and the
    /// objects of `names` can arrive in another order. The detached metadata
    /// goes in one of the streams, after its objects.
    ///
    /// The object streams of all the calls of the session stay within
    /// `parallel-uploads`, at most 31. A stream waits for a permit. After the
    /// first failure, no stream starts a new object, and each stream reads its
    /// response.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if the level of `compression` is not 1
    ///   through 9, or if the type of a name is not a file, a dirtree, a
    ///   dirmeta, a commit, or a composefs image. The call sends nothing, and
    ///   the session stays usable.
    /// - [`Error::InvalidInput`] if another call runs, as the rules of
    ///   [concurrent calls](PushSession#concurrent-calls) state, or if the
    ///   session is broken.
    /// - [`Error::Source`] if the source fails. The session ends with
    ///   `Abort`.
    /// - [`Error::InvalidInput`] if the source gives data that the session
    ///   cannot send, for example a symlink with a payload, or detached
    ///   metadata that [`DetachedMetadata`] refuses. The session ends with
    ///   `Abort`.
    /// - An `Error` message from the server, as the [`Error`] variant of its
    ///   code.
    /// - [`Error::Protocol`] for a malformed reply, or for a reply that is
    ///   not `ObjectsReply`.
    /// - [`Error::LimitExceeded`] on a stream transport, for a frame over the
    ///   frame limit.
    /// - [`Error::Io`] for a failure of the stream, or for a failed read of a
    ///   response body over HTTP.
    /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
    /// - [`Error::Transport`] over HTTP, for a status other than 200, 401,
    ///   403, 409, 422, 500, and 503, or for a body that is not one frame. A
    ///   404 for a session that the server ended is such a status.
    ///
    /// If more than one object stream fails over HTTP, the call returns one
    /// error, in this order:
    ///
    /// 1. [`Error::Source`] or [`Error::InvalidInput`], a failure of the client
    /// 2. an error with a wire code, for example an error that the server gave
    ///    for its own cause
    /// 3. any other error, also the [`Error::Protocol`] of a stream that ends
    ///    because the server aborted the session for the failure of another
    ///    stream
    ///
    /// # Panics
    ///
    /// Under the `tokio` backend, the call panics outside a tokio runtime
    /// context if the source gives a [`DetachedMetadata::Dict`] for a commit
    /// of `commits`. A session over ssh or HTTP also needs this context, as
    /// [`connect`](PushSession::connect) states.
    pub async fn send(
        &self,
        source: &dyn ObjectSource,
        names: &[ObjectName],
        commits: &[Checksum],
        compression: Compression,
    ) -> Result<()> {
        let level = deflate_level(compression)?;
        refuse_off_wire(names)?;
        let deflate_ok = self.inner.server.encodings.contains(&Encoding::Deflate);
        let level = level.filter(|_| deflate_ok);
        let upload = Upload::new(
            source,
            names,
            commits,
            level,
            deflate_ok,
            &self.inner.claims,
        );
        let counters = &self.inner.counters;
        let slot = match &self.inner.link {
            Link::Stream { slot, .. } => slot,
            Link::Http(link) => {
                count_content_total(counters, source, names, level).await;
                counters.phase(PushPhase::Uploading);
                return link.send(counters, &upload).await;
            }
        };
        let mut taken = take(slot)?;
        count_content_total(counters, source, names, level).await;
        counters.phase(PushPhase::Uploading);
        taken.stream().upload(&upload).await?;
        taken.release();
        Ok(())
    }

    /// Sends `Commit` with `updates`, and returns the outcome from the reply.
    ///
    /// The call consumes the session. The call sends no `Commit` if it refuses
    /// `updates`, if the session is broken, or if the `Commit` frame is over
    /// the frame limit. On a stream transport it then sends nothing, so the
    /// server reads the end of the stream. Over HTTP, it sends `DELETE`.
    ///
    /// Over ssh, the call then waits for the ssh client to exit, also after a
    /// refusal. The ssh time limits of [`connect`](PushSession::connect) give
    /// the rules of the wait.
    ///
    /// # HTTP
    ///
    /// The client sends the `Commit` request once, and never sends it again.
    /// If the client did not hand the request over to a connection, the
    /// server changed no ref. After the hand-over, these failures are
    /// [`Error::CommitOutcomeUnknown`]:
    ///
    /// - a failure of the request
    /// - a response head that the client refuses, for example for a declared
    ///   coding or for a declared length over the cap
    /// - a failed read of the response
    /// - a status other than 200, 401, 403, 409, 422, 500, and 503, for
    ///   example the 404 of a session that the server ended
    /// - a body that is not one frame
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if `updates` is empty, names a ref that
    ///   `Hello` did not name, or names a ref twice.
    /// - [`Error::InvalidInput`] if the session is broken.
    /// - [`Error::LimitExceeded`] if the `Commit` frame is over the frame
    ///   limit.
    /// - An `Error` message from the server, as the [`Error`] variant of its
    ///   code. An ostrya server sends it before it changes a ref, with two
    ///   exceptions. A failed write of the refs can leave some refs written,
    ///   and a failure of a hook after the update keeps all the refs.
    /// - [`Error::Fetch`] over HTTP, if the client did not hand the request
    ///   over to a connection.
    /// - [`Error::CommitOutcomeUnknown`] for each other end of the session
    ///   after the session wrote `Commit`. The server can have written the
    ///   refs. A `CommitReply` whose refs are not the refs of `updates` in
    ///   order is one of these cases.
    ///
    /// If the write of `Commit` fails with an I/O error, the session reads one
    /// message. An `Error` message gives the [`Error`] variant of its code,
    /// and a `CommitReply` gives the outcome. Any other result is
    /// [`Error::CommitOutcomeUnknown`].
    pub async fn commit(self, updates: &[RefUpdate], force: bool) -> Result<PushOutcome> {
        let checked = check_updates(&self.inner.server.refs, updates);
        let request = CommitRequest {
            updates: updates.to_vec(),
            force,
            server_commit: None,
        };
        let names = updates.iter().map(|u| u.name.clone()).collect();
        // The future of the commit is large. The box keeps it out of the
        // future of this call.
        Box::pin(self.inner.send_commit(checked, request, names)).await
    }

    /// Checks the server commit `sc` against the session, and sends nothing.
    ///
    /// The check is the check of [`server_commit`](PushSession::server_commit)
    /// before it sends `Commit`. A caller runs it after the session opens and
    /// before it offers or sends an object, so that a refused server commit
    /// sends no object.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if `Hello` did not name the branch or a tag
    ///   of `sc`, or if `sc` names a ref twice among its branch and its
    ///   tags.
    /// - [`Error::Protocol`] if the bytes of a metadata entry of `sc` are not
    ///   a `v` in normal form.
    /// - [`Error::InvalidInput`] if a commit cannot hold a metadata value of
    ///   `sc`. A commit holds 128 levels of containers, counted from its
    ///   metadata dict, so the value can hold two levels fewer than a `v`.
    /// - [`Error::LimitExceeded`] if the `CommitReply` to `sc` can need a
    ///   frame over the `max-frame` of the server. The longest reply holds
    ///   the branch with an old and a new commit, and each tag with a new
    ///   commit.
    /// - [`Error::LimitExceeded`] if the `Commit` frame that holds `sc` is
    ///   over the `max-frame` of the server.
    pub fn check_server_commit(&self, sc: &ServerCommit) -> Result<()> {
        check_server_commit_fields(&self.inner.server, sc)?;
        let limit = self.inner.server.max_frame;
        let len = server_commit_frame_len(sc)?;
        if len > u64::from(limit) {
            return Err(Error::LimitExceeded(format!(
                "the Commit frame of the server commit is {len} bytes, over the limit {limit} \
                 of the server"
            )));
        }
        Ok(())
    }

    /// Sends `Commit` with the server commit `sc`, and returns the outcome
    /// from the reply.
    ///
    /// The server makes a commit over the root dirtree and the root dirmeta
    /// of `sc`. It moves the branch of `sc` to the commit and creates each
    /// tag at it, in one transaction. [`PushOutcome::commit`] gives the new
    /// commit, and [`PushOutcome::refs`] gives the outcome of the branch,
    /// then of each tag.
    ///
    /// The call consumes the session. It sends no detached metadata. It
    /// runs the checks of
    /// [`check_server_commit`](PushSession::check_server_commit) before it
    /// writes `Commit`. The encode of the `Commit` frame checks the length of
    /// the frame, so the call encodes the frame one time. If a check fails,
    /// or if the session is broken, the call sends no `Commit` and ends the
    /// session as [`commit`](PushSession::commit) does. The rules of
    /// the HTTP request and of the wait for the ssh client are those of
    /// [`commit`](PushSession::commit).
    ///
    /// # Errors
    ///
    /// - Each error of
    ///   [`check_server_commit`](PushSession::check_server_commit).
    /// - [`Error::InvalidInput`] if the session is broken.
    /// - An `Error` message from the server, as the [`Error`] variant of its
    ///   code. An ostrya server sends it before it changes a ref. Examples
    ///   are [`Error::RefDenied`] for a client with no `c` on the branch, or
    ///   for a server that runs hooks, and [`Error::RefMismatch`] for a tag
    ///   that exists.
    /// - [`Error::Fetch`] over HTTP, if the client did not hand the request
    ///   over to a connection.
    /// - [`Error::CommitOutcomeUnknown`] for each other end of the session
    ///   after the session wrote `Commit`. The server can have written the
    ///   refs. A `CommitReply` that does not hold the branch and then each
    ///   tag, each at one new commit, with no old commit for a tag, is one of
    ///   these cases.
    pub async fn server_commit(self, sc: ServerCommit) -> Result<PushOutcome> {
        // The send path refuses a frame over the `max-frame` of the server
        // before it writes a byte.
        let checked = check_server_commit_fields(&self.inner.server, &sc);
        let names: Vec<String> = server_commit_refs(&sc).map(str::to_owned).collect();
        let request = CommitRequest {
            updates: Vec::new(),
            force: false,
            server_commit: Some(Box::new(sc)),
        };
        let mut outcome = Box::pin(self.inner.send_commit(checked, request, names)).await?;
        outcome.commit = Some(server_commit_checksum(&outcome.refs)?);
        Ok(outcome)
    }

    /// Ends the session, so that the server aborts its transaction.
    ///
    /// On a stream transport, if the stream is usable, the session writes
    /// `Abort` and closes its output. A broken session has no stream, so the
    /// call writes nothing. Over ssh, the call then waits for the ssh client to
    /// exit, as the ssh time limits of [`connect`](PushSession::connect) state.
    ///
    /// Over HTTP, the call sends `DELETE`, also on a broken session. A 204 is
    /// success, and so is a 404, which the server gives for a session that it
    /// ended already.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if the session is broken. Over HTTP, the
    ///   call sends `DELETE` first.
    /// - [`Error::Io`] if the write of `Abort` fails.
    /// - [`Error::Transport`] over ssh, if the write of `Abort` fails with an
    ///   I/O error and the ssh client exits with a failure status. The error
    ///   names the status.
    /// - An `Error` message from the server over HTTP, as the [`Error`]
    ///   variant of its code.
    /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
    /// - [`Error::Transport`] over HTTP, for a status that the endpoint does
    ///   not give, or for a body that is not one frame.
    /// - [`Error::Io`] over HTTP, for a failed read of the response body.
    pub async fn abort(self) -> Result<()> {
        let (slot, transport) = match self.inner.link {
            Link::Stream { slot, transport } => (slot, transport),
            Link::Http(link) => return link.abort().await,
        };
        let result = match into_stream(slot) {
            Ok(mut stream) => {
                let result = stream.write_raw(&Message::Abort).await;
                let _ = stream.close().await;
                result
            }
            Err(e) => Err(e),
        };
        finish(transport, result).await
    }
}

/// A session that commits: the parts of a stream session, or the commit of
/// an HTTP session. The value lives for one match, so the size of the
/// stream variant costs nothing.
#[allow(clippy::large_enum_variant)]
enum Committing {
    Stream {
        slot: Mutex<Slot>,
        transport: Option<Transport>,
        counters: Arc<Counters>,
        checked: Result<()>,
        request: CommitRequest,
        names: Vec<String>,
    },
    /// The HTTP commit holds the response of its request, so its future is
    /// boxed, and the future of a stream commit does not hold it.
    Http(BoxFuture<'static, Result<PushOutcome>>),
}

impl SessionInner {
    /// Takes the session apart to send `request`, which `checked` checked.
    /// `names` are the refs that the `CommitReply` must hold, in order.
    fn into_commit(
        self,
        checked: Result<()>,
        request: CommitRequest,
        names: Vec<String>,
    ) -> Committing {
        let SessionInner {
            server,
            counters,
            link,
            ..
        } = self;
        match link {
            Link::Stream { slot, transport } => Committing::Stream {
                slot,
                transport,
                counters,
                checked,
                request,
                names,
            },
            Link::Http(link) => Committing::Http(Box::pin(async move {
                link.commit(&server, &counters, checked, request, &names)
                    .await
            })),
        }
    }

    /// Sends `Commit` with `request`, which `checked` checked, and returns
    /// the outcome from the reply. `names` are the refs that the
    /// `CommitReply` must hold, in order.
    async fn send_commit(
        self,
        checked: Result<()>,
        request: CommitRequest,
        names: Vec<String>,
    ) -> Result<PushOutcome> {
        let (slot, transport, counters, checked, request, names) =
            match self.into_commit(checked, request, names) {
                Committing::Stream {
                    slot,
                    transport,
                    counters,
                    checked,
                    request,
                    names,
                } => (slot, transport, counters, checked, request, names),
                Committing::Http(commit) => return commit.await,
            };
        let stream = into_stream(slot);
        let result = match (checked, stream) {
            (Ok(()), Ok(stream)) => commit_on(stream, request, &names, &counters).await,
            (Ok(()), Err(e)) => Err(e),
            (Err(e), stream) => {
                // The server reads the end of the stream.
                drop(stream);
                Err(e)
            }
        };
        finish(transport, result).await
    }
}

/// Returns the refs that the server commit `sc` writes: the branch, then
/// each tag.
fn server_commit_refs(sc: &ServerCommit) -> impl Iterator<Item = &str> {
    std::iter::once(sc.branch.as_str()).chain(sc.tags.iter().map(String::as_str))
}

/// Runs the checks of a server commit `sc` against the facts of `server`,
/// other than the length of the `Commit` frame: the names of the refs, the
/// depth of each metadata value, and the length of the longest
/// `CommitReply`.
fn check_server_commit_fields(server: &ServerInfo, sc: &ServerCommit) -> Result<()> {
    let named: HashSet<&str> = server.refs.iter().map(|r| r.name.as_str()).collect();
    let mut seen = HashSet::new();
    for name in server_commit_refs(sc) {
        if !named.contains(name) {
            return Err(invalid(format!(
                "ref '{name}' was not named when the session opened"
            )));
        }
        if !seen.insert(name) {
            return Err(invalid(format!(
                "ref '{name}' is named twice in the server commit"
            )));
        }
    }
    check_server_commit_metadata(sc)?;
    let limit = server.max_frame;
    let len = server_commit_reply_frame_len(sc)?;
    if len > u64::from(limit) {
        return Err(Error::LimitExceeded(format!(
            "the reply to the server commit with {} tags can need a frame of {len} bytes, over \
             the limit {limit} of the server",
            sc.tags.len()
        )));
    }
    Ok(())
}

/// Returns the commit of the `CommitReply` of a server commit, whose ref
/// names the session checked.
///
/// Each ref must have one new commit, and a tag must have no old commit.
/// Else the result is [`Error::CommitOutcomeUnknown`].
fn server_commit_checksum(refs: &[RefOutcome]) -> Result<Checksum> {
    let commit = refs.first().and_then(|branch| branch.new);
    match commit {
        Some(commit)
            if refs.iter().all(|r| r.new == Some(commit))
                && refs.iter().skip(1).all(|tag| tag.old.is_none()) =>
        {
            Ok(commit)
        }
        _ => Err(Error::CommitOutcomeUnknown {
            refs: refs.iter().map(|r| r.name.clone()).collect(),
            message: "the server replied to the server commit with refs that are not each at \
                      one new commit"
                .into(),
        }),
    }
}

/// Refuses empty `updates`, a ref that is not in `refs`, and a ref named
/// twice.
fn check_updates(refs: &[RefState], updates: &[RefUpdate]) -> Result<()> {
    if updates.is_empty() {
        return Err(invalid("a commit needs at least one ref update"));
    }
    let mut seen = HashSet::new();
    for u in updates {
        if !refs.iter().any(|r| r.name == u.name) {
            return Err(invalid(format!(
                "ref '{}' was not named when the session opened",
                u.name
            )));
        }
        if !seen.insert(u.name.as_str()) {
            return Err(invalid(format!("ref '{}' is updated twice", u.name)));
        }
    }
    Ok(())
}

/// Ends a session with `result`. A session with a transport waits for it to
/// finish. The stream of the session must be closed or dropped first.
async fn finish<T>(transport: Option<Transport>, result: Result<T>) -> Result<T> {
    match transport {
        Some(transport) => transport.finish(result).await,
        None => result,
    }
}

/// Sends `Commit` with `request` over `stream` and reads the reply. The
/// reply must hold the refs `names`, in order. The stream is closed or
/// dropped when the call returns.
async fn commit_on(
    mut stream: Box<Stream>,
    request: CommitRequest,
    names: &[String],
    counters: &Counters,
) -> Result<PushOutcome> {
    counters.phase(PushPhase::Committing);
    let unknown = |message: String| Error::CommitOutcomeUnknown {
        refs: names.to_vec(),
        message,
    };
    let request = Message::Commit(request);
    let reply = match stream.write_raw(&request).await {
        Ok(()) => stream.read_raw().await,
        Err(e @ Error::Io(_)) => match stream.pending_message(&e).await {
            Some(msg @ (Message::Error(_) | Message::CommitReply(_))) => Ok(Some(msg)),
            _ => return Err(unknown(format!("the write of Commit failed: {e}"))),
        },
        Err(e) => return Err(e),
    };
    let refs = match reply {
        Ok(Some(Message::CommitReply(refs))) => refs,
        Ok(Some(Message::Error(e))) => return Err(e.into()),
        Ok(Some(other)) => {
            return Err(unknown(format!("{:?} in reply to Commit", other.kind())));
        }
        Ok(None) => return Err(unknown("the session ended before CommitReply".into())),
        Err(e) => return Err(unknown(format!("the reply to Commit failed: {e}"))),
    };
    if !reply_names_match(&refs, names) {
        return Err(unknown(
            "the server replied to Commit for other refs than the refs of Commit".into(),
        ));
    }
    // The refs are written. A failure to close the stream changes nothing.
    let _ = stream.close().await;
    Ok(PushOutcome {
        commit: None,
        refs,
        stats: counters.stats(),
    })
}

/// Returns `true` if the outcomes `refs` of a `CommitReply` name the refs
/// `names`, in order.
fn reply_names_match(refs: &[RefOutcome], names: &[String]) -> bool {
    refs.len() == names.len() && refs.iter().zip(names).all(|(o, n)| o.name == *n)
}