ostrya-remote 0.6.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
//! The HTTP transport of a session.
//!
//! Each step of a session is one request to the receive endpoint of the
//! server, and each response body holds one frame. The calls of one session
//! share one gate of `parallel-uploads` permits, at most [`MAX_PARALLEL`].

use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Poll, Wake, Waker};
use std::time::Duration;

use futures_io::{AsyncRead, AsyncWrite};
use futures_lite::io::AsyncReadExt;
use ostrya_core::ObjectName;
use ostrya_fetch::gate::Gate;
use ostrya_fetch::{Fetcher, Priority, UploadBody, UploadMethod, UploadRequest, Uploaded};

use super::progress::Counters;
use super::writer::{Counting, Item, ObjectWriter, Pass, Stop, Upload};
use super::{
    BoxFuture, PushOutcome, PushPhase, ServerInfo, broken, invalid, server_info, unexpected,
};
use crate::error::{Error, Result};
use crate::proto::{
    CommitRequest, FrameReader, Hello, MAX_FRAME, MIN_FRAME_LIMIT, Message, PROTOCOL_VERSION,
    encode_frame, have_entries_within,
};

/// The path of the receive endpoint under the push address, with the step
/// that opens a session.
const SESSION_PATH: &str = "_ostrya/receive/v1/session";

/// The response header that names a new session.
const SESSION_HEADER: &str = "ostrya-session";

/// The longest wait for the response to `Hello` after the client sent the
/// request body.
const HELLO_RESPONSE: Duration = Duration::from_secs(360);

/// The longest wait for the response to `Commit` after the client sent the
/// request body. The response comes after the commit checks and the ref
/// writes.
const COMMIT_RESPONSE: Duration = Duration::from_secs(3600);

/// The most object streams of one session, whatever the server announces.
/// The fetcher of a session admits one request more, so `Have` and `Commit`
/// never wait for the object streams at the gate of the fetcher.
pub(crate) const MAX_PARALLEL: u32 = 31;

/// The start of the message of an error that the server gives to a step
/// after it aborted the session for another cause.
const SESSION_ABORTED: &str = "the session was aborted";

/// The receive endpoint of a server, as an HTTP session reaches it.
///
/// `transport::http::prepare` builds it from the options of an HTTP
/// `transport::Endpoint`.
pub(crate) struct Endpoint {
    /// The fetcher, with the push address as its one mirror. It carries the
    /// credential of each request.
    pub(crate) fetcher: Fetcher,
    /// The push address, which the messages name.
    pub(crate) url: String,
}

/// The result of one upload request.
type Sent = std::result::Result<Uploaded, ostrya_fetch::Error>;

impl Endpoint {
    /// Sends one request to `path` under the push address.
    ///
    /// `timeout` bounds the wait for the response after the body is sent. If
    /// `timeout` is `None`, the wait takes the progress timeout of the
    /// fetcher. The future of an upload is large, so the call boxes it, and
    /// the future of each step holds a pointer to it.
    fn request<'a>(
        &'a self,
        path: &'a str,
        method: UploadMethod,
        body: UploadBody,
        timeout: Option<Duration>,
    ) -> BoxFuture<'a, Sent> {
        let mut request = UploadRequest::path(path, body);
        request.method = method;
        request.response_timeout = timeout;
        Box::pin(self.fetcher.upload(request))
    }

    /// Sends the whole body `body` to `path` with `POST`, as
    /// [`request`](Self::request) does.
    ///
    /// The bytes of the body count as sent when the fetcher hands the request
    /// to a connection. This is true if the upload gives a response, and if
    /// the upload fails after the hand-over.
    async fn post(
        &self,
        path: &str,
        body: Vec<u8>,
        timeout: Option<Duration>,
        counters: &Counters,
    ) -> Sent {
        let len = body.len() as u64;
        let sent = self
            .request(path, UploadMethod::Post, UploadBody::bytes(body), timeout)
            .await;
        if sent.as_ref().map_or_else(|e| !e.is_unsent(), |_| true) {
            counters.wire(len);
        }
        sent
    }

    /// Returns the URL of `path`, for the text of an error.
    fn url_of(&self, path: &str) -> String {
        format!("{}/{path}", self.url.trim_end_matches('/'))
    }
}

/// One session over HTTP.
pub(crate) struct HttpLink {
    endpoint: Endpoint,
    /// The path of the session under the push address.
    session: String,
    /// The permits of the object streams of the session.
    gate: Arc<Gate>,
    /// The number of permits of `gate`.
    permits: usize,
    /// The frame and chunk limit of the server.
    max_frame: u32,
    /// `true` after a call fails, or after the future of a call is dropped
    /// before it completes.
    broken: AtomicBool,
    /// `true` while a `missing` call runs.
    have_busy: AtomicBool,
}

/// A guard that marks the session broken if a call fails, or if the future
/// of the call is dropped before it completes.
struct Call<'a> {
    broken: &'a AtomicBool,
    completed: bool,
}

impl<'a> Call<'a> {
    fn new(broken: &'a AtomicBool) -> Call<'a> {
        Call {
            broken,
            completed: false,
        }
    }

    fn complete(mut self) {
        self.completed = true;
    }
}

impl Drop for Call<'_> {
    fn drop(&mut self) {
        if !self.completed {
            self.broken.store(true, Ordering::Relaxed);
        }
    }
}

/// A guard that clears the flag of a `missing` call when the call ends.
struct Busy<'a> {
    flag: &'a AtomicBool,
}

impl Drop for Busy<'_> {
    fn drop(&mut self) {
        self.flag.store(false, Ordering::Relaxed);
    }
}

/// Reads the message of the body of a response with `status` from `url`.
///
/// The body of a 200 holds one frame. The body of a 401, a 403, a 409, a
/// 422, a 500, and a 503 holds one frame of an `Error` message. These cases
/// are [`Error::Transport`], which names the URL and the status:
///
/// - each other status,
/// - a body that is not one frame,
/// - a frame other than an `Error` message with one of the error statuses.
///
/// A failed read of the body is [`Error::Io`]. The reader takes frames of at
/// most [`MAX_FRAME`] bytes, whatever the server announced.
async fn decode_reply<R: AsyncRead + Unpin>(status: u16, url: &str, body: R) -> Result<Message> {
    if !matches!(status, 200 | 401 | 403 | 409 | 422 | 500 | 503) {
        return Err(Error::Transport(format!(
            "{url} answered with the status {status}"
        )));
    }
    let not_a_frame = |why: &str| {
        Error::Transport(format!(
            "{url} answered with the status {status} and a body that is not one frame: {why}"
        ))
    };
    let mut reader = FrameReader::new(body);
    reader.set_limit(MAX_FRAME);
    let msg = match reader.read_message().await {
        Ok(Some(msg)) => msg,
        Ok(None) => return Err(not_a_frame("the body is empty")),
        Err(Error::Io(e)) => return Err(Error::Io(e)),
        Err(e) => return Err(not_a_frame(&e.to_string())),
    };
    let mut byte = [0u8; 1];
    if reader.into_inner().read(&mut byte).await? != 0 {
        return Err(not_a_frame("bytes follow the frame"));
    }
    match msg {
        Message::Error(_) => Ok(msg),
        _ if status == 200 => Ok(msg),
        other => Err(not_a_frame(&format!(
            "a {:?} frame comes with an error status",
            other.kind()
        ))),
    }
}

/// Reads the message of the response `uploaded` from `url` with
/// [`decode_reply`].
///
/// The future holds the response body and a frame reader, so the call boxes
/// it. The future of each step holds a pointer to it.
fn reply(uploaded: Uploaded, url: &str) -> BoxFuture<'_, Result<Message>> {
    let status = uploaded.status();
    Box::pin(decode_reply(status, url, uploaded.into_body()))
}

/// Returns the session id of the [`SESSION_HEADER`] header of `uploaded`, if
/// the id is 64 lowercase hex digits.
fn session_id(uploaded: &Uploaded) -> Option<String> {
    let id = uploaded.headers().get(SESSION_HEADER)?.to_str().ok()?;
    let valid = id.len() == 64 && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
    valid.then(|| id.to_owned())
}

/// Opens a session: sends `Hello` with `refs` and `collection`, and reads
/// `HelloReply`.
///
/// If a check of the reply fails after the server opened the session, the
/// call ends the session with `DELETE`.
pub(super) async fn open(
    endpoint: Endpoint,
    refs: &[String],
    agent: String,
    collection: Option<String>,
    counters: &Counters,
) -> Result<(ServerInfo, HttpLink)> {
    let hello = Message::Hello(Hello {
        version: PROTOCOL_VERSION,
        agent: Some(agent),
        refs: refs.to_vec(),
        collection: collection.clone(),
        one_way: false,
    });
    let body = encode_frame(&hello, MIN_FRAME_LIMIT)?;
    let url = endpoint.url_of(SESSION_PATH);
    let uploaded = endpoint
        .post(SESSION_PATH, body, Some(HELLO_RESPONSE), counters)
        .await
        .map_err(Error::Fetch)?;
    let id = session_id(&uploaded);
    let reply = match reply(uploaded, &url).await? {
        Message::HelloReply(reply) => reply,
        Message::Error(e) => return Err(e.into()),
        other => return Err(unexpected(&other, "Hello")),
    };
    let Some(id) = id else {
        return Err(Error::Transport(format!(
            "{url} answered HelloReply with no session id of 64 lowercase hex digits in the \
             {SESSION_HEADER} header"
        )));
    };
    let max_frame = reply.max_frame;
    let permits = reply.parallel_uploads.clamp(1, MAX_PARALLEL) as usize;
    let link = HttpLink {
        endpoint,
        session: format!("{SESSION_PATH}/{id}"),
        gate: Arc::new(Gate::new(permits)),
        permits,
        max_frame,
        broken: AtomicBool::new(false),
        have_busy: AtomicBool::new(false),
    };
    match server_info(reply, refs, collection.as_deref()) {
        Ok(server) => Ok((server, link)),
        Err(e) => {
            let _ = link.delete().await;
            Err(e)
        }
    }
}

/// Returns the number of object streams of a `send` call of `names` names
/// with `permits` permits.
///
/// The number is one for each permit, no more than `names`, and at least
/// one. The one stream of a call with no name sends the detached metadata.
fn worker_count(permits: usize, names: usize) -> usize {
    permits.min(names.max(1))
}

/// Returns the rank of an error of one object stream of a `send` call.
///
/// A `send` call returns the error of the lowest rank:
///
/// - 0: an error of the client, [`Error::Source`] or [`Error::InvalidInput`].
/// - 1: each other error with a wire code. Examples are an error that the
///   server gave for its own cause, and an [`Error::Protocol`] that the
///   client makes for a frame that it refuses.
/// - 2: each other error, and an [`Error::Protocol`] whose message starts
///   with [`SESSION_ABORTED`]. That is the error that a step gets after the
///   server aborted the session for the cause of another stream.
fn rank(e: &Error) -> u8 {
    match e {
        Error::Source(_) | Error::InvalidInput(_) => 0,
        Error::Protocol(m) if m.starts_with(SESSION_ABORTED) => 2,
        e if e.code().is_some() => 1,
        _ => 2,
    }
}

/// Returns the error of a `Commit` request whose upload failed with `e`.
///
/// If the fetcher did not hand the request over, the failure is definite,
/// and the error is [`Error::Fetch`]. A request that the fetcher handed over
/// can have reached the server. Each failure after the hand-over is then the
/// error that `unknown` makes, and the client does not send the request again.
fn commit_failure(e: ostrya_fetch::Error, unknown: impl FnOnce(String) -> Error) -> Error {
    if e.is_unsent() {
        Error::Fetch(e)
    } else {
        unknown(e.to_string())
    }
}

/// The future of one object stream of a `send` call.
type Worker<'f> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'f>>;

/// The wake-ups of the workers of one [`join_workers`] call.
///
/// Each worker has its own waker. The waker records the worker and wakes the
/// task of the call. The call then polls only the workers that woke.
struct Woken {
    /// One bit for each worker that woke since the call last polled it.
    due: AtomicU32,
    /// The waker of the task that polls the call.
    task: Mutex<Option<Waker>>,
}

/// The waker of worker `index` of a [`join_workers`] call.
struct WorkerWaker {
    index: usize,
    woken: Arc<Woken>,
}

impl Wake for WorkerWaker {
    fn wake(self: Arc<Self>) {
        self.wake_by_ref();
    }

    fn wake_by_ref(self: &Arc<Self>) {
        self.woken.due.fetch_or(1 << self.index, Ordering::AcqRel);
        // The task wakes after the lock is released.
        let task = self
            .woken
            .task
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone();
        if let Some(task) = task {
            task.wake();
        }
    }
}

/// Runs `workers` to their end in the task of the caller and returns the
/// errors of the failed workers.
///
/// The errors are in the order in which they came. At the first error, the
/// call runs `stop` and then waits for every worker to end. The first poll of
/// the call polls each worker. After that, the call polls a worker only when
/// the waker of that worker wakes.
///
/// The call keeps the waker of the task before it reads the due workers. A
/// worker that wakes during a poll of the call then wakes the task again, so
/// no wake-up is lost. One call runs at most 32 workers, and more workers cause
/// a panic.
async fn join_workers(workers: Vec<Worker<'_>>, stop: impl Fn()) -> Vec<Error> {
    assert!(workers.len() <= 32, "a call runs at most 32 workers");
    // A worker that ends is dropped at once.
    let mut workers: Vec<Option<Worker<'_>>> = workers.into_iter().map(Some).collect();
    let all = u32::MAX.checked_shr(32 - workers.len() as u32).unwrap_or(0);
    let woken = Arc::new(Woken {
        due: AtomicU32::new(all),
        task: Mutex::new(None),
    });
    let wakers: Vec<Waker> = (0..workers.len())
        .map(|index| {
            Waker::from(Arc::new(WorkerWaker {
                index,
                woken: Arc::clone(&woken),
            }))
        })
        .collect();
    let mut live = all;
    let mut errors = Vec::new();
    std::future::poll_fn(|cx| {
        {
            let mut task = woken.task.lock().unwrap_or_else(PoisonError::into_inner);
            if !task.as_ref().is_some_and(|t| t.will_wake(cx.waker())) {
                *task = Some(cx.waker().clone());
            }
        }
        let mut due = woken.due.swap(0, Ordering::AcqRel) & live;
        while due != 0 {
            let index = due.trailing_zeros() as usize;
            due &= due - 1;
            let Some(worker) = &mut workers[index] else {
                continue;
            };
            let mut worker_cx = Context::from_waker(&wakers[index]);
            if let Poll::Ready(result) = worker.as_mut().poll(&mut worker_cx) {
                workers[index] = None;
                live &= !(1 << index);
                if let Err(e) = result {
                    stop();
                    errors.push(e);
                }
            }
        }
        if live == 0 {
            Poll::Ready(())
        } else {
            Poll::Pending
        }
    })
    .await;
    errors
}

/// The end of the write side of one object stream.
enum Written {
    /// The stream ended with `ObjectsEnd`, and the body is closed.
    Done,
    /// The source failed or gave data that the session cannot send. The
    /// stream ended with `Abort`.
    Abandoned(Error),
    /// A write failed. The body is dropped while it is open, so the request
    /// fails.
    Failed(Error),
}

/// Writes the object stream of one request: `first`, the items of `up` that
/// `pass` takes after it, and `ObjectsEnd`.
///
/// A failure stops `up`. The output is dropped when the call returns, so a
/// body that is not closed fails.
async fn write_stream<W: AsyncWrite + Unpin>(
    mut out: ObjectWriter<W>,
    first: std::result::Result<Item, Stop>,
    up: &Upload<'_>,
    mut pass: Pass,
) -> Written {
    let mut started = true;
    let written = match first {
        Ok(item) => match out.write_item(item).await {
            Ok(()) => out.write_items(up, &mut pass, &mut started).await,
            Err(stop) => Err(stop),
        },
        Err(stop) => Err(stop),
    };
    match written {
        Ok(()) => {
            if let Err(e) = out.frames().write_message(&Message::ObjectsEnd).await {
                up.stop();
                return Written::Failed(e);
            }
            match out.close().await {
                Ok(()) => Written::Done,
                Err(e) => {
                    up.stop();
                    Written::Failed(e)
                }
            }
        }
        Err(Stop::Wire(e)) => {
            up.stop();
            Written::Failed(e)
        }
        Err(Stop::Abandon {
            error, in_object, ..
        }) => {
            up.stop();
            // The upload ends with the error of the stop, so a failed write
            // is ignored.
            let _ = out.abandon(in_object).await;
            let _ = out.close().await;
            Written::Abandoned(error)
        }
    }
}

impl HttpLink {
    /// Returns the path of the step `step` of the session.
    fn step_path(&self, step: &str) -> String {
        format!("{}/{step}", self.session)
    }

    /// Sends `body` to the step `step` and reads the message of the response.
    async fn step(&self, step: &str, body: Vec<u8>, counters: &Counters) -> Result<Message> {
        let path = self.step_path(step);
        let uploaded = self
            .endpoint
            .post(&path, body, None, counters)
            .await
            .map_err(Error::Fetch)?;
        reply(uploaded, &self.endpoint.url_of(&path)).await
    }

    /// Ends the session on the server with `DELETE`.
    ///
    /// The call returns `Ok` for a 204 and for a 404. The server gives a 404
    /// for a session that it ended already.
    async fn delete(&self) -> Result<()> {
        let url = self.endpoint.url_of(&self.session);
        let uploaded = self
            .endpoint
            .request(
                &self.session,
                UploadMethod::Delete,
                UploadBody::bytes(Vec::new()),
                None,
            )
            .await
            .map_err(Error::Fetch)?;
        match uploaded.status() {
            204 | 404 => Ok(()),
            _ => match reply(uploaded, &url).await? {
                Message::Error(e) => Err(e.into()),
                other => Err(Error::Transport(format!(
                    "{url} answered DELETE with {:?}",
                    other.kind()
                ))),
            },
        }
    }

    /// Returns the objects of `names` that the server does not hold, as
    /// [`PushSession::missing`](super::PushSession::missing) states.
    ///
    /// Each `Have` is one request. The next `Have` waits for the response to
    /// the `Have` before it.
    pub(super) async fn missing(
        &self,
        server: &ServerInfo,
        counters: &Counters,
        names: &[ObjectName],
    ) -> Result<Vec<ObjectName>> {
        if self.broken.load(Ordering::Relaxed) {
            return Err(broken());
        }
        if self.have_busy.swap(true, Ordering::Relaxed) {
            return Err(invalid("a call is in progress"));
        }
        let _busy = Busy {
            flag: &self.have_busy,
        };
        let call = Call::new(&self.broken);
        counters.phase(PushPhase::Negotiating);
        counters.offered(names);
        let mut missing = Vec::new();
        let batch_len = server
            .max_have
            .min(have_entries_within(server.max_frame))
            .max(1);
        for batch in names.chunks(batch_len as usize) {
            let body = encode_frame(&Message::Have(batch.to_vec()), server.max_frame)?;
            match self.step("have", body, counters).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);
        call.complete();
        Ok(missing)
    }

    /// Sends the objects of `up` over object streams of their own, as
    /// [`PushSession::send`](super::PushSession::send) states.
    ///
    /// The call runs one object stream for each permit of the session, up to
    /// one for each name, and polls them in its own task. Each stream waits
    /// for a permit of the session gate, so the streams of all the calls of
    /// the session stay within the permits. After the first error, no stream
    /// takes a new name.
    ///
    /// Each stream reads its response. The call then returns the error of the
    /// lowest [`rank`].
    pub(super) async fn send(&self, counters: &Arc<Counters>, up: &Upload<'_>) -> Result<()> {
        if self.broken.load(Ordering::Relaxed) {
            return Err(broken());
        }
        let call = Call::new(&self.broken);
        let workers: Vec<Worker<'_>> = (0..worker_count(self.permits, up.names.len()))
            .map(|_| Box::pin(self.object_stream(counters, up)) as Worker<'_>)
            .collect();
        let errors = join_workers(workers, || up.stop()).await;
        let first = errors
            .into_iter()
            .enumerate()
            .min_by_key(|(i, e)| (rank(e), *i))
            .map(|(_, e)| e);
        match first {
            Some(e) => Err(e),
            None => {
                call.complete();
                Ok(())
            }
        }
    }

    /// Sends one object stream of a `send` call in one `objects` request.
    ///
    /// The stream takes a permit and the first item, and then sends the items
    /// of `up`. A stream that finds no item sends no request.
    async fn object_stream(&self, counters: &Arc<Counters>, up: &Upload<'_>) -> Result<()> {
        let _permit = self.gate.acquire(Priority::Normal).await;
        let (body, writer) = UploadBody::channel();
        let output = Counting::new(writer, Arc::clone(counters));
        let mut out = ObjectWriter::new(output, Arc::clone(counters));
        out.frames().set_limit(self.max_frame);
        let mut pass = Pass::default();
        let first = match out.next_item(up, &mut pass).await {
            Ok(None) => return Ok(()),
            Ok(Some(item)) => Ok(item),
            Err(stop) => {
                up.stop();
                Err(stop)
            }
        };
        let path = self.step_path("objects");
        let url = self.endpoint.url_of(&path);
        // This future reads the response to its end, which also ends a body
        // that is still open. The write side then cannot wait for a request
        // that is over.
        let response = async {
            let uploaded = self
                .endpoint
                .request(&path, UploadMethod::Post, body, None)
                .await
                .map_err(Error::Fetch)?;
            reply(uploaded, &url).await
        };
        let write = write_stream(out, first, up, pass);
        let (reply, written) = futures_lite::future::zip(response, write).await;
        match written {
            Written::Done => match reply? {
                Message::ObjectsReply(_) => Ok(()),
                Message::Error(e) => Err(e.into()),
                other => Err(unexpected(&other, "ObjectsEnd")),
            },
            Written::Abandoned(error) => Err(error),
            // A write fails if the request failed, or if the server answered
            // before the end of the body. The response gives the cause.
            Written::Failed(e) => Err(match reply {
                Ok(Message::Error(sent)) => sent.into(),
                Ok(_) => e,
                Err(r) => r,
            }),
        }
    }

    /// Sends `Commit` with `request`, as
    /// [`PushSession::commit`](super::PushSession::commit) states. The reply
    /// must hold the refs `names`, in order.
    ///
    /// The call ends the session with `DELETE` and sends no `Commit` in these
    /// cases:
    ///
    /// - `checked` is an error.
    /// - The session is broken.
    /// - The codec refuses the `Commit`.
    pub(super) async fn commit(
        self,
        server: &ServerInfo,
        counters: &Counters,
        checked: Result<()>,
        request: CommitRequest,
        names: &[String],
    ) -> Result<PushOutcome> {
        if let Err(e) = checked {
            let _ = self.delete().await;
            return Err(e);
        }
        if self.broken.load(Ordering::Relaxed) {
            let _ = self.delete().await;
            return Err(broken());
        }
        counters.phase(PushPhase::Committing);
        let request = Message::Commit(request);
        let body = match encode_frame(&request, server.max_frame) {
            Ok(body) => body,
            Err(e) => {
                let _ = self.delete().await;
                return Err(e);
            }
        };
        drop(request);
        let unknown = |message: String| Error::CommitOutcomeUnknown {
            refs: names.to_vec(),
            message,
        };
        let path = self.step_path("commit");
        let sent = self
            .endpoint
            .post(&path, body, Some(COMMIT_RESPONSE), counters)
            .await;
        let uploaded = sent.map_err(|e| commit_failure(e, unknown))?;
        let refs = match reply(uploaded, &self.endpoint.url_of(&path)).await {
            Ok(Message::CommitReply(refs)) => refs,
            Ok(Message::Error(e)) => return Err(e.into()),
            Ok(other) => {
                return Err(unknown(format!("{:?} in reply to Commit", other.kind())));
            }
            Err(e) => return Err(unknown(format!("the reply to Commit failed: {e}"))),
        };
        if !super::reply_names_match(&refs, names) {
            return Err(unknown(
                "the server replied to Commit for other refs than the refs of Commit".into(),
            ));
        }
        Ok(PushOutcome {
            commit: None,
            refs,
            stats: counters.stats(),
        })
    }

    /// Ends the session with `DELETE`.
    ///
    /// If the session is broken, the call also sends `DELETE` and then returns
    /// [`Error::InvalidInput`].
    pub(super) async fn abort(self) -> Result<()> {
        let was_broken = self.broken.load(Ordering::Relaxed);
        let deleted = self.delete().await;
        if was_broken {
            return Err(broken());
        }
        deleted
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::proto::{ErrorMessage, ObjectsReply};
    use crate::{ErrorCode, RefOutcome, RefState};

    fn encode(msg: &Message) -> Vec<u8> {
        encode_frame(msg, MAX_FRAME).unwrap()
    }

    fn decode(status: u16, body: &[u8]) -> Result<Message> {
        ostrya_rt::block_on(decode_reply(status, "https://h/x", body))
    }

    fn error_frame(code: ErrorCode) -> Vec<u8> {
        // A `ref-mismatch` carries the current state of its ref.
        let current = (code == ErrorCode::RefMismatch).then(|| RefState {
            name: "main".into(),
            commit: None,
        });
        encode(&Message::Error(ErrorMessage {
            code,
            message: "m".into(),
            missing: Vec::new(),
            current,
        }))
    }

    fn transport(r: Result<Message>, part: &str) {
        match r {
            Err(Error::Transport(m)) => {
                assert!(m.contains("https://h/x"), "{m}");
                assert!(m.contains(part), "{m:?} lacks {part:?}");
            }
            other => panic!("expected Transport, got {other:?}"),
        }
    }

    /// A 200 gives its one frame. Each status that carries an `Error`
    /// message gives the frame of that message.
    #[test]
    fn a_frame_status_gives_its_frame() {
        let reply = Message::ObjectsReply(ObjectsReply {
            objects: 2,
            payload_bytes: 9,
        });
        assert!(matches!(
            decode(200, &encode(&reply)),
            Ok(Message::ObjectsReply(_))
        ));
        let committed = Message::CommitReply(vec![RefOutcome {
            name: "main".into(),
            old: None,
            new: None,
        }]);
        assert!(matches!(
            decode(200, &encode(&committed)),
            Ok(Message::CommitReply(_))
        ));
        for (status, code) in [
            (401, ErrorCode::Unauthorized),
            (403, ErrorCode::Unauthorized),
            (409, ErrorCode::RefMismatch),
            (409, ErrorCode::NonFastForward),
            (422, ErrorCode::ChecksumMismatch),
            (500, ErrorCode::Internal),
            (503, ErrorCode::LimitExceeded),
            (200, ErrorCode::Protocol),
        ] {
            match decode(status, &error_frame(code)) {
                Ok(Message::Error(e)) => {
                    assert_eq!(e.code, code, "{status}");
                    assert_eq!(Error::from(e).code(), Some(code), "{status}");
                }
                other => panic!("{status}: {other:?}"),
            }
        }
    }

    /// Each other status is `Error::Transport`, which names the URL and the
    /// status, whatever the body holds.
    #[test]
    fn another_status_is_a_transport_error() {
        for status in [201, 204, 301, 302, 307, 308, 400, 404, 405, 413, 502, 504] {
            transport(decode(status, b""), &format!("status {status}"));
            transport(
                decode(status, &error_frame(ErrorCode::Internal)),
                &format!("status {status}"),
            );
        }
    }

    /// A body that is not one frame is `Error::Transport`: an empty body,
    /// text, bytes after the frame, a frame over the limit of the client, and
    /// a reply frame with an error status. A cut frame is `Error::Io`.
    #[test]
    fn a_body_that_is_not_one_frame_is_a_transport_error() {
        transport(decode(200, b""), "the body is empty");
        transport(decode(422, b""), "the body is empty");
        transport(decode(200, b"<html>bad gateway</html>"), "not one frame");
        transport(decode(500, b"Internal Server Error"), "not one frame");
        let mut two = error_frame(ErrorCode::Internal);
        two.extend_from_slice(&error_frame(ErrorCode::Internal));
        transport(decode(500, &two), "bytes follow the frame");
        let mut over = (MAX_FRAME + 1).to_be_bytes().to_vec();
        over.push(10);
        transport(decode(200, &over), "limit");
        let reply = encode(&Message::ObjectsReply(ObjectsReply {
            objects: 0,
            payload_bytes: 0,
        }));
        transport(decode(422, &reply), "error status");
        // A cut frame is a failed read of the body.
        let cut = &error_frame(ErrorCode::Internal)[..6];
        assert!(matches!(decode(500, cut), Err(Error::Io(_))));
    }

    /// The future of a `send` call holds the state of both transports. The
    /// object streams of an HTTP call are boxed, so the size of the future
    /// does not grow with them.
    #[test]
    fn the_send_future_is_small() {
        use crate::proto::{Encoding, HelloReply};
        use crate::{Compression, ObjectData, ObjectSource, PushSession, SessionOptions};

        struct NoSource;
        impl ObjectSource for NoSource {
            fn objects<'a>(
                &'a self,
                _: &'a ostrya_core::Checksum,
            ) -> crate::BoxFuture<'a, Result<Vec<ObjectName>>> {
                Box::pin(async { Ok(Vec::new()) })
            }
            fn open<'a>(
                &'a self,
                _: &'a ObjectName,
                _: Encoding,
            ) -> crate::BoxFuture<'a, Result<ObjectData>> {
                Box::pin(async { Err(invalid("no object")) })
            }
            fn detached_metadata<'a>(
                &'a self,
                _: &'a ostrya_core::Checksum,
            ) -> crate::BoxFuture<'a, Result<Option<ostrya_gvariant::Value>>> {
                Box::pin(async { Ok(None) })
            }
        }
        let reply = encode(&Message::HelloReply(HelloReply {
            version: PROTOCOL_VERSION,
            mode: "archive".into(),
            collection_id: None,
            collection: None,
            max_frame: MIN_FRAME_LIMIT,
            max_have: 16_384,
            encodings: vec![Encoding::Raw],
            parallel_uploads: 1,
            refs: Vec::new(),
        }));
        let session = ostrya_rt::block_on(PushSession::over_stream(
            futures_lite::io::Cursor::new(reply),
            futures_lite::io::sink(),
            &[],
            SessionOptions::default(),
        ))
        .unwrap();
        let send = session.send(&NoSource, &[], &[], Compression::None);
        let size = std::mem::size_of_val(&send);
        eprintln!("the send future is {size} bytes");
        assert!(size <= 4096, "the send future is {size} bytes");
    }

    /// The futures of `missing`, `commit`, `server_commit`, `connect`, its two
    /// steps, and the tree pushes hold the state of both transports. The upload request, the
    /// read of its reply, and the construction of the fetcher are boxed, so
    /// none of them sits inline in these futures.
    #[test]
    fn the_session_futures_are_small() {
        use crate::proto::{Encoding, HelloReply};
        use crate::{
            Endpoint, PushSession, SessionOptions, TreePushOptions, push_tree, push_tree_prepared,
        };

        let reply = encode(&Message::HelloReply(HelloReply {
            version: PROTOCOL_VERSION,
            mode: "archive".into(),
            collection_id: None,
            collection: None,
            max_frame: MIN_FRAME_LIMIT,
            max_have: 16_384,
            encodings: vec![Encoding::Raw],
            parallel_uploads: 1,
            refs: vec![crate::RefState {
                name: "main".into(),
                commit: None,
            }],
        }));
        let open = || {
            ostrya_rt::block_on(PushSession::over_stream(
                futures_lite::io::Cursor::new(reply.clone()),
                futures_lite::io::sink(),
                &["main".to_owned()],
                SessionOptions::default(),
            ))
            .unwrap()
        };
        let session = open();
        let missing = std::mem::size_of_val(&session.missing(&[]));
        let commit = std::mem::size_of_val(&open().commit(&[], false));
        let server_commit =
            std::mem::size_of_val(&open().server_commit(crate::proto::ServerCommit {
                branch: "main".into(),
                tags: Vec::new(),
                bind_refs: Vec::new(),
                root_dirtree: ostrya_core::Checksum::from_bytes([1; 32]),
                root_dirmeta: ostrya_core::Checksum::from_bytes([2; 32]),
                subject: String::new(),
                body: String::new(),
                metadata: Vec::new(),
                timestamp: None,
                orphan: false,
            }));
        let endpoint = Endpoint::parse("https://h/repo").unwrap();
        let refs = ["main".to_owned()];
        let connect = std::mem::size_of_val(&PushSession::connect(
            endpoint.clone(),
            &refs,
            SessionOptions::default(),
        ));
        let root = std::path::Path::new("/nonexistent");
        let tree = std::mem::size_of_val(&push_tree(
            endpoint.clone(),
            root,
            TreePushOptions::default(),
        ));
        let prepare = std::mem::size_of_val(&PushSession::prepare(endpoint));
        // An ssh address needs no runtime to prepare.
        let ssh = Endpoint::parse("ssh://h/repo").unwrap();
        let prepared = || ostrya_rt::block_on(PushSession::prepare(ssh.clone())).unwrap();
        let open = std::mem::size_of_val(&prepared().open(&refs, SessionOptions::default()));
        let tree_prepared = std::mem::size_of_val(&push_tree_prepared(
            prepared(),
            root,
            TreePushOptions::default(),
        ));
        eprintln!(
            "missing {missing}, commit {commit}, server_commit {server_commit}, \
             connect {connect}, prepare {prepare}, open {open}, push_tree {tree}, \
             push_tree_prepared {tree_prepared} bytes"
        );
        assert!(missing <= 1024, "the missing future is {missing} bytes");
        assert!(commit <= 3072, "the commit future is {commit} bytes");
        assert!(
            server_commit <= 3072,
            "the server_commit future is {server_commit} bytes"
        );
        assert!(connect <= 4096, "the connect future is {connect} bytes");
        assert!(prepare <= 2048, "the prepare future is {prepare} bytes");
        assert!(open <= 4096, "the open future is {open} bytes");
        assert!(tree <= 6144, "the push_tree future is {tree} bytes");
        assert!(
            tree_prepared <= 6144,
            "the push_tree_prepared future is {tree_prepared} bytes"
        );
    }

    /// A `Commit` request that the fetcher did not hand over is a definite
    /// failure. Each failure after the hand-over leaves the outcome unknown.
    /// This includes a response that the fetcher refuses for its coding.
    #[test]
    fn a_commit_failure_after_the_hand_over_is_unknown() {
        let unknown = |message: String| Error::CommitOutcomeUnknown {
            refs: vec!["main".into()],
            message,
        };
        let unsent = ostrya_fetch::Error::Fetch("connect to h:443 failed".into());
        assert!(matches!(
            commit_failure(unsent, unknown),
            Error::Fetch(ostrya_fetch::Error::Fetch(_))
        ));
        let coded = ostrya_fetch::Error::UploadInterrupted {
            url: "https://h/commit".into(),
            message: "response for https://h/commit carries the coding gzip".into(),
        };
        match commit_failure(coded, unknown) {
            Error::CommitOutcomeUnknown { refs, message } => {
                assert_eq!(refs, ["main"]);
                assert!(message.contains("coding gzip"), "{message}");
            }
            other => panic!("expected an unknown outcome, got {other:?}"),
        }
    }

    /// A worker is polled when the call starts and then when its own waker
    /// wakes. The other workers are not polled for it, and a wake-up during
    /// a poll of the call is not lost.
    #[test]
    fn join_polls_the_workers_that_woke() {
        use std::sync::atomic::AtomicUsize;

        /// A worker that counts its polls and ends once `done` is set.
        struct Probe {
            polls: Arc<AtomicUsize>,
            done: Arc<AtomicBool>,
            waker: Arc<Mutex<Option<Waker>>>,
        }
        impl Future for Probe {
            type Output = Result<()>;
            fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
                self.polls.fetch_add(1, Ordering::SeqCst);
                if self.done.load(Ordering::SeqCst) {
                    return Poll::Ready(Ok(()));
                }
                *self.waker.lock().unwrap() = Some(cx.waker().clone());
                Poll::Pending
            }
        }
        /// The waker of the task, which counts its wakes.
        struct Task(AtomicUsize);
        impl Wake for Task {
            fn wake(self: Arc<Self>) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }

        let probes: Vec<_> = (0..3)
            .map(|_| {
                (
                    Arc::new(AtomicUsize::new(0)),
                    Arc::new(AtomicBool::new(false)),
                    Arc::new(Mutex::new(None::<Waker>)),
                )
            })
            .collect();
        let workers: Vec<Worker<'_>> = probes
            .iter()
            .map(|(polls, done, waker)| {
                Box::pin(Probe {
                    polls: Arc::clone(polls),
                    done: Arc::clone(done),
                    waker: Arc::clone(waker),
                }) as Worker<'_>
            })
            .collect();
        let polls = |i: usize| probes[i].0.load(Ordering::SeqCst);
        let wake = |i: usize| probes[i].2.lock().unwrap().take().unwrap().wake();
        let task = Arc::new(Task(AtomicUsize::new(0)));
        let task_waker = Waker::from(Arc::clone(&task));
        let mut cx = Context::from_waker(&task_waker);
        let mut join = std::pin::pin!(join_workers(workers, || {}));

        assert!(join.as_mut().poll(&mut cx).is_pending());
        assert_eq!([polls(0), polls(1), polls(2)], [1, 1, 1]);
        // A poll with no wake-up polls no worker.
        assert!(join.as_mut().poll(&mut cx).is_pending());
        assert_eq!([polls(0), polls(1), polls(2)], [1, 1, 1]);

        wake(1);
        assert_eq!(task.0.load(Ordering::SeqCst), 1);
        assert!(join.as_mut().poll(&mut cx).is_pending());
        assert_eq!([polls(0), polls(1), polls(2)], [1, 2, 1]);

        // Two wake-ups before the next poll: both workers are polled once.
        probes[0].1.store(true, Ordering::SeqCst);
        wake(0);
        wake(2);
        assert!(join.as_mut().poll(&mut cx).is_pending());
        assert_eq!([polls(0), polls(1), polls(2)], [2, 2, 2]);

        probes[1].1.store(true, Ordering::SeqCst);
        probes[2].1.store(true, Ordering::SeqCst);
        wake(1);
        wake(2);
        assert!(join.as_mut().poll(&mut cx).is_ready());
        assert_eq!([polls(0), polls(1), polls(2)], [2, 3, 3]);
    }

    /// At the first error, the call stops the upload, waits for the other
    /// workers, and returns each error.
    #[test]
    fn join_stops_at_the_first_error_and_waits_for_every_worker() {
        let stopped = AtomicBool::new(false);
        let workers: Vec<Worker<'_>> = vec![
            Box::pin(async { Err(invalid("first")) }),
            Box::pin(async {
                // The worker yields once, so it ends after the error.
                futures_lite::future::yield_now().await;
                Ok(())
            }),
            Box::pin(async { Err(Error::Transport("second".into())) }),
        ];
        let errors = ostrya_rt::block_on(join_workers(workers, || {
            stopped.store(true, Ordering::SeqCst)
        }));
        assert!(stopped.load(Ordering::SeqCst));
        assert_eq!(errors.len(), 2);
        // A call with no worker ends at once.
        assert!(ostrya_rt::block_on(join_workers(Vec::new(), || {})).is_empty());
    }

    /// A call runs one stream for each permit, no more than one for each
    /// name, and one for a call with no name.
    #[test]
    fn the_streams_of_a_call_are_bounded_by_the_permits_and_the_names() {
        assert_eq!(worker_count(1, 1000), 1);
        assert_eq!(worker_count(3, 1000), 3);
        assert_eq!(worker_count(31, 2), 2);
        assert_eq!(worker_count(4, 0), 1);
        assert_eq!(worker_count(4, 1), 1);
        assert_eq!(worker_count(4, 4), 4);
    }

    /// An error of the client wins over an error of the server. An error of
    /// the server wins over the error of a step that failed because of the
    /// abort of the session.
    #[test]
    fn the_error_of_a_call_is_chosen_by_rank() {
        let source = Error::Source("read failed".into());
        let local = invalid("bad data");
        let server = Error::ChecksumMismatch("object".into());
        let cascade = Error::Protocol(format!("{SESSION_ABORTED}: checksum-mismatch"));
        let other = Error::Io(std::io::ErrorKind::BrokenPipe.into());
        assert_eq!(rank(&source), 0);
        assert_eq!(rank(&local), 0);
        assert_eq!(rank(&server), 1);
        assert_eq!(rank(&Error::Protocol("bad frame".into())), 1);
        assert_eq!(rank(&cascade), 2);
        assert_eq!(rank(&other), 2);
        assert_eq!(rank(&Error::Transport("x".into())), 2);
    }
}