Skip to main content

ostrya_remote/session/
mod.rs

1//! The client sessions of the push and of the pull, and the one-way stream.
2//!
3//! A [`PushSession`] opens with `Hello` and gives the facts of the server as
4//! [`ServerInfo`]. Its calls are:
5//!
6//! - [`missing`](PushSession::missing) asks the server which objects it needs.
7//! - [`send`](PushSession::send) sends them from an [`ObjectSource`], with the
8//!   detached metadata of their commits.
9//! - [`commit`](PushSession::commit) asks the server to update its refs in
10//!   one transaction.
11//! - [`server_commit`](PushSession::server_commit) asks the server to make a
12//!   commit over a tree that it holds, and to move a branch to it.
13//!
14//! [`PushProgress`] counts the progress of a session, and [`PushOutcome`]
15//! gives the result of a session that committed.
16//!
17//! A [`StreamSession`] reads files and ref listings of a server repository,
18//! and gives each body as a [`PullBody`]. A [`PullSession`] reads the summary
19//! and the ref listings of a remote over HTTP or over a stream session.
20//!
21//! [`export_stream`] writes a one-way stream: the messages of a push session in
22//! one direction, for a receiver that sends no reply.
23
24pub(crate) mod http;
25mod one_way;
26mod progress;
27mod pull;
28mod pull_session;
29pub(crate) mod stream;
30mod writer;
31
32use std::collections::HashSet;
33use std::fmt;
34use std::future::Future;
35use std::pin::Pin;
36use std::sync::{Arc, Mutex, PoisonError};
37use std::time::Duration;
38
39use futures_io::{AsyncRead, AsyncWrite};
40use ostrya_core::{Checksum, FileHeader, ObjectName, ObjectType, Ref};
41use ostrya_gvariant::Value;
42
43pub use one_way::export_stream;
44pub use progress::{PushPhase, PushProgress, PushProgressFn, PushProgressSnapshot, PushStats};
45pub use pull::{PullBody, StreamSession, StreamSessionOptions};
46pub use pull_session::PullSession;
47
48use self::http::{Endpoint, HttpLink};
49use self::progress::Counters;
50use self::stream::Stream;
51use self::writer::{MetaClaims, Upload};
52use crate::error::{Error, Result};
53use crate::proto::{
54    CommitRequest, Encoding, Hello, HelloReply, Message, PROTOCOL_VERSION, RefOutcome, RefState,
55    RefUpdate, ServerCommit, check_server_commit_metadata, have_entries_within, have_type,
56    protocol, server_commit_frame_len, server_commit_reply_frame_len,
57};
58use crate::transport::Transport;
59
60/// A boxed `Send` future, the return type of the [`ObjectSource`] methods.
61pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
62
63/// The encoding of the content objects that a session sends.
64#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
65pub enum Compression {
66    /// The `raw` encoding: the framed file header and the payload.
67    #[default]
68    None,
69    /// The `deflate` encoding at `level`, 1 through 9.
70    ///
71    /// The session uses it if the server lists `deflate`. If the server lists
72    /// `raw` alone, the session sends `raw`.
73    Deflate {
74        /// The compression level, 1 through 9.
75        level: u8,
76    },
77}
78
79/// A stream of object bytes that a source gives to the session.
80pub trait ObjectReader: AsyncRead + Send + Sync + Unpin {}
81
82impl<T: AsyncRead + Send + Sync + Unpin + ?Sized> ObjectReader for T {}
83
84/// The data of one object, as an [`ObjectSource`] gives it.
85pub enum ObjectData {
86    /// A content object that the session encodes.
87    ///
88    /// `header` is the file header of the object, and `size` is the length of
89    /// its payload. A regular file has a `payload`. A symlink has no `payload`
90    /// and a `size` of 0.
91    ///
92    /// For `raw`, the session sends the framed header and the payload. For
93    /// `deflate`, it sends the framed archive header, and then the payload
94    /// through its own raw-DEFLATE compressor.
95    Content {
96        /// The file header.
97        header: FileHeader,
98        /// The length of the payload, in bytes.
99        size: u64,
100        /// The payload of a regular file.
101        payload: Option<Box<dyn ObjectReader>>,
102    },
103    /// The object bytes in `encoding`, which the session copies as they are.
104    ///
105    /// A metadata object is `raw` alone. The session sends a content object in
106    /// `raw` as `raw`, also if it deflates. Bytes in `deflate` for a metadata
107    /// object, or for a server that does not list `deflate`, are
108    /// [`Error::InvalidInput`].
109    Encoded {
110        /// The encoding of the bytes.
111        encoding: Encoding,
112        /// The bytes.
113        reader: Box<dyn ObjectReader>,
114    },
115}
116
117impl fmt::Debug for ObjectData {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        match self {
120            ObjectData::Content {
121                header,
122                size,
123                payload,
124            } => f
125                .debug_struct("Content")
126                .field("header", header)
127                .field("size", size)
128                .field("payload", &payload.is_some())
129                .finish(),
130            ObjectData::Encoded { encoding, .. } => f
131                .debug_struct("Encoded")
132                .field("encoding", encoding)
133                .finish_non_exhaustive(),
134        }
135    }
136}
137
138/// The detached metadata of a commit, as an [`ObjectSource`] gives it.
139///
140/// [`ObjectSource::detached_metadata_encoded`] returns it. The session
141/// serializes a [`Dict`](DetachedMetadata::Dict) on the blocking pool of
142/// `ostrya-rt`. Under the `tokio` backend, this pool is the blocking pool of
143/// the tokio runtime, so the serialization panics outside a tokio runtime
144/// context.
145///
146/// If a dict does not serialize as `a{sv}`, the object stream stops with
147/// [`Error::InvalidInput`]. If the bytes of either form are more than 128 MiB
148/// ([`MAX_METADATA_SIZE`](ostrya_core::MAX_METADATA_SIZE)), the object stream
149/// also stops with [`Error::InvalidInput`]. An ostrya server refuses bytes
150/// that are not a normal-form `a{sv}` dict with the code `protocol`.
151pub enum DetachedMetadata {
152    /// An `a{sv}` dict, which the session serializes.
153    Dict(Value),
154    /// The bytes of an `a{sv}` dict in normal form.
155    ///
156    /// The session sends the bytes as they are, and checks only their length.
157    Encoded(Vec<u8>),
158}
159
160/// A source of the objects that a session sends.
161pub trait ObjectSource: Send + Sync {
162    /// Returns the name of each object that `commit` reaches, and of the commit.
163    ///
164    /// No session method calls `objects`. A caller gives the list to
165    /// [`missing`](PushSession::missing) to find the objects to
166    /// [`send`](PushSession::send).
167    ///
168    /// # Errors
169    ///
170    /// The error depends on the implementation:
171    ///
172    /// - [`TreeModel`](crate::tree::TreeModel) returns [`Error::InvalidInput`],
173    ///   because the model holds no commit.
174    /// - The repository source of the `ostrya` crate returns
175    ///   [`Error::Source`] if the walk of `commit` in the repository fails.
176    fn objects<'a>(&'a self, commit: &'a Checksum) -> BoxFuture<'a, Result<Vec<ObjectName>>>;
177
178    /// Returns the data of the object `name`.
179    ///
180    /// `encoding` is the encoding in which the session sends the object:
181    /// `deflate` for a content object if the session deflates, and `raw` for
182    /// all other objects. A source that holds the object in that encoding can
183    /// give its bytes as [`ObjectData::Encoded`].
184    ///
185    /// # Errors
186    ///
187    /// An error of the source stops the object stream.
188    /// [`send`](PushSession::send) and [`export_stream`] return it as
189    /// [`Error::Source`].
190    fn open<'a>(
191        &'a self,
192        name: &'a ObjectName,
193        encoding: Encoding,
194    ) -> BoxFuture<'a, Result<ObjectData>>;
195
196    /// Returns the detached metadata for `commit`, an `a{sv}` dict.
197    ///
198    /// The source applies its own filter first. For `None`, the session sends
199    /// no detached metadata for `commit`. [`DetachedMetadata`] gives the
200    /// checks of the dict.
201    ///
202    /// The session calls this method only through the default implementation
203    /// of
204    /// [`detached_metadata_encoded`](ObjectSource::detached_metadata_encoded).
205    /// A source that overrides that method must still implement this one.
206    ///
207    /// # Errors
208    ///
209    /// An error of the source stops the object stream.
210    /// [`send`](PushSession::send) and [`export_stream`] return it as
211    /// [`Error::Source`].
212    fn detached_metadata<'a>(
213        &'a self,
214        commit: &'a Checksum,
215    ) -> BoxFuture<'a, Result<Option<Value>>>;
216
217    /// Returns the detached metadata for `commit`, as a dict or as its bytes.
218    ///
219    /// The session sends the detached metadata of each commit through this
220    /// method. The default implementation calls
221    /// [`detached_metadata`](ObjectSource::detached_metadata) and gives its
222    /// dict as [`DetachedMetadata::Dict`]. A source that holds the bytes of
223    /// the dict can give them as [`DetachedMetadata::Encoded`].
224    ///
225    /// For `None`, the session sends no detached metadata for `commit`.
226    /// [`DetachedMetadata`] gives the checks of each form.
227    ///
228    /// # Errors
229    ///
230    /// An error of the source stops the object stream.
231    /// [`send`](PushSession::send) and [`export_stream`] return it as
232    /// [`Error::Source`].
233    fn detached_metadata_encoded<'a>(
234        &'a self,
235        commit: &'a Checksum,
236    ) -> BoxFuture<'a, Result<Option<DetachedMetadata>>> {
237        Box::pin(async move {
238            Ok(self
239                .detached_metadata(commit)
240                .await?
241                .map(DetachedMetadata::Dict))
242        })
243    }
244
245    /// Returns the content bytes of the file objects of `names` in `encoding`.
246    ///
247    /// `None` means that the source does not know the number. The names that
248    /// are not file objects count no byte. The default implementation returns
249    /// `None`.
250    ///
251    /// The content bytes of one file object are the bytes that the session
252    /// reads from the reader that [`open`](ObjectSource::open) gives for it
253    /// with the same `encoding`:
254    ///
255    /// - the payload of [`ObjectData::Content`]
256    /// - 0 for a symlink
257    /// - the bytes of [`ObjectData::Encoded`]
258    ///
259    /// If the session has a [`PushProgress`] and `names` holds at least one
260    /// file object, each [`send`](PushSession::send) call and each
261    /// [`export_stream`] call asks once, before the first object. The call
262    /// adds the answer to [`bytes_total`](PushProgressSnapshot::bytes_total).
263    ///
264    /// The method must not read the content of an object. It reads what the
265    /// source already holds, or the metadata of each object.
266    ///
267    /// # Errors
268    ///
269    /// The session treats an error as `None`. The call adds nothing to the
270    /// total and sends the objects.
271    fn content_size<'a>(
272        &'a self,
273        names: &'a [ObjectName],
274        encoding: Encoding,
275    ) -> BoxFuture<'a, Result<Option<u64>>> {
276        let _ = (names, encoding);
277        Box::pin(async { Ok(None) })
278    }
279}
280
281/// The facts of the server, from its `HelloReply`.
282#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct ServerInfo {
284    /// The protocol version of the session.
285    pub version: u32,
286    /// The repository mode.
287    pub mode: String,
288    /// The collection id of the repository.
289    ///
290    /// The refs of this collection are the local refs of the server.
291    pub collection_id: Option<String>,
292    /// The frame and chunk limit that the session writes with.
293    ///
294    /// The value is in
295    /// [`MIN_FRAME_LIMIT`](crate::proto::MIN_FRAME_LIMIT)`..=`[`MAX_FRAME_LIMIT`](crate::proto::MAX_FRAME_LIMIT).
296    pub max_frame: u32,
297    /// The highest number of object names in one `Have`.
298    pub max_have: u32,
299    /// The content encodings that the server accepts.
300    pub encodings: Vec<Encoding>,
301    /// The most object streams that the server serves at the same time.
302    pub parallel_uploads: u32,
303    /// The state of each ref that the session named, in the order of the names.
304    pub refs: Vec<RefState>,
305}
306
307impl ServerInfo {
308    /// Returns the canonical form of `r` on the server.
309    ///
310    /// A collection ref of the [`collection_id`](ServerInfo::collection_id)
311    /// of the server is the local ref of the same name. Each other ref is
312    /// unchanged. The call does not check the ref. [`Ref::canonical`] gives
313    /// the same form in a repository.
314    pub fn canonical(&self, r: &Ref) -> Ref {
315        r.clone().canonical(self.collection_id.as_deref())
316    }
317
318    /// Returns the current commit of the ref `name` on the server.
319    ///
320    /// Returns `None` if the ref is absent, or if the session did not name it.
321    pub fn tip(&self, name: &str) -> Option<Checksum> {
322        self.refs
323            .iter()
324            .find(|r| r.name == name)
325            .and_then(|r| r.commit)
326    }
327}
328
329/// The options of a session.
330#[derive(Debug, Clone, Default)]
331pub struct SessionOptions {
332    /// The `agent` that the session sends in `Hello`.
333    ///
334    /// The default is `ostrya/<version>`.
335    pub agent: Option<String>,
336    /// A handle that the session also counts its progress into.
337    pub progress: Option<PushProgress>,
338}
339
340/// The result of a push that committed.
341#[derive(Debug, Clone, PartialEq, Eq)]
342pub struct PushOutcome {
343    /// The commit that the server made for
344    /// [`server_commit`](PushSession::server_commit).
345    ///
346    /// A session that ends with [`commit`](PushSession::commit) gives
347    /// `None`.
348    pub commit: Option<Checksum>,
349    /// One outcome for each ref update, in the order of the updates.
350    pub refs: Vec<RefOutcome>,
351    /// The statistics of the session.
352    pub stats: PushStats,
353}
354
355/// A client session of a push, over a stream transport or over HTTP.
356///
357/// [`connect`](PushSession::connect) opens a session over ssh or HTTP, and
358/// [`prepare`](PushSession::prepare) checks the transport before the open.
359/// [`over_stream`](PushSession::over_stream) opens a session over a pair of
360/// byte streams.
361///
362/// If the caller drops a session without [`commit`](PushSession::commit),
363/// [`server_commit`](PushSession::server_commit), or
364/// [`abort`](PushSession::abort), the session sends nothing more. A stream
365/// transport then closes its output, so the server reads the end of the
366/// stream. Over HTTP, the server ends the session when its idle timeout ends.
367///
368/// After the server ends a session over HTTP, it answers each later request
369/// of that session with 404. The session reports a 404 on
370/// [`missing`](PushSession::missing) or [`send`](PushSession::send) as
371/// [`Error::Transport`], and a 404 on [`commit`](PushSession::commit) or
372/// [`server_commit`](PushSession::server_commit) as
373/// [`Error::CommitOutcomeUnknown`].
374///
375/// # Verification
376///
377/// The session does not verify the objects that it sends. It computes no
378/// checksum and checks no size. The server verifies each object when it
379/// arrives. If a source fails while the session sends an object, the session
380/// abandons the object with the abandon marker and ends the session with
381/// `Abort`.
382///
383/// # Concurrent calls
384///
385/// The session is `Send + Sync`. On a stream transport, the session runs one
386/// call at a time. A call to [`missing`](PushSession::missing) or
387/// [`send`](PushSession::send) while another call runs fails at once with
388/// [`Error::InvalidInput`].
389///
390/// Over HTTP, several [`send`](PushSession::send) calls can run at the same
391/// time, and a [`missing`](PushSession::missing) call can run beside them. A
392/// second `missing` call while one runs fails at once with
393/// [`Error::InvalidInput`].
394///
395/// On both transports, a call that fails, or whose future the caller drops
396/// before it completes, leaves the session broken. Each later call then fails
397/// with [`Error::InvalidInput`]. If `missing` or `send` refuses an argument,
398/// the call sends nothing and the session stays usable.
399pub struct PushSession {
400    inner: SessionInner,
401}
402
403struct SessionInner {
404    server: ServerInfo,
405    counters: Arc<Counters>,
406    /// The claims of the detached metadata the session sends.
407    claims: MetaClaims,
408    link: Link,
409}
410
411/// The transport of a session.
412enum Link {
413    /// A pair of byte streams.
414    Stream {
415        slot: Mutex<Slot>,
416        /// The child process the streams belong to, for a session that
417        /// [`PushSession::connect`] opened.
418        transport: Option<Transport>,
419    },
420    /// The receive endpoint of an HTTP server.
421    Http(HttpLink),
422}
423
424enum Slot {
425    /// No call runs.
426    Idle(Box<Stream>),
427    /// A call runs and holds the stream.
428    Busy,
429    /// A call failed or was dropped. The stream is gone.
430    Poisoned,
431}
432
433/// The stream a call holds. The call gives it back with
434/// [`release`](Taken::release) when it completes. Dropped without a release,
435/// it leaves the session broken.
436struct Taken<'a> {
437    slot: &'a Mutex<Slot>,
438    stream: Option<Box<Stream>>,
439}
440
441impl Taken<'_> {
442    fn stream(&mut self) -> &mut Stream {
443        self.stream.as_mut().expect("the stream is held")
444    }
445
446    fn release(mut self) {
447        let stream = self.stream.take().expect("the stream is held");
448        *self.slot.lock().unwrap_or_else(PoisonError::into_inner) = Slot::Idle(stream);
449    }
450}
451
452impl Drop for Taken<'_> {
453    fn drop(&mut self) {
454        if self.stream.is_some() {
455            *self.slot.lock().unwrap_or_else(PoisonError::into_inner) = Slot::Poisoned;
456        }
457    }
458}
459
460pub(crate) fn invalid(msg: impl Into<String>) -> Error {
461    Error::InvalidInput(msg.into())
462}
463
464pub(super) fn broken() -> Error {
465    invalid("the session is broken")
466}
467
468pub(super) fn unexpected(msg: &Message, request: &str) -> Error {
469    protocol(format!("{:?} in reply to {request}", msg.kind()))
470}
471
472/// The DEFLATE level of `compression`, or `None` for `raw`. A level outside 1
473/// through 9 is [`Error::InvalidInput`].
474pub(crate) fn deflate_level(compression: Compression) -> Result<Option<u8>> {
475    match compression {
476        Compression::None => Ok(None),
477        Compression::Deflate { level } if (1..=9).contains(&level) => Ok(Some(level)),
478        Compression::Deflate { level } => Err(invalid(format!(
479            "compression level {level} is not in 1 through 9"
480        ))),
481    }
482}
483
484/// Asks `source` for the content bytes of the file objects of `names`, sent
485/// at `level`, and adds them to the byte total of `counters`. A session with
486/// no caller's handle, and names with no file object, ask nothing. An
487/// unknown size and a failure add nothing.
488async fn count_content_total(
489    counters: &Counters,
490    source: &dyn ObjectSource,
491    names: &[ObjectName],
492    level: Option<u8>,
493) {
494    if !counters.has_caller() || !names.iter().any(|n| n.ty == ObjectType::File) {
495        return;
496    }
497    let encoding = match level {
498        Some(_) => Encoding::Deflate,
499        None => Encoding::Raw,
500    };
501    if let Ok(Some(total)) = source.content_size(names, encoding).await {
502        counters.content_total(total);
503    }
504}
505
506/// Refuses a name of a type that `Have` and the objects of a source cannot
507/// carry. The session sends detached metadata for a commit on its own.
508fn refuse_off_wire(names: &[ObjectName]) -> Result<()> {
509    match names.iter().find(|n| !have_type(n.ty)) {
510        Some(n) => Err(invalid(format!(
511            "object {} of type {:?} is not an object to offer or send",
512            n.checksum, n.ty
513        ))),
514        None => Ok(()),
515    }
516}
517
518/// Takes the stream of `slot` for one call.
519fn take(slot: &Mutex<Slot>) -> Result<Taken<'_>> {
520    let mut held = slot.lock().unwrap_or_else(PoisonError::into_inner);
521    match std::mem::replace(&mut *held, Slot::Busy) {
522        Slot::Idle(stream) => Ok(Taken {
523            slot,
524            stream: Some(stream),
525        }),
526        Slot::Busy => Err(invalid("a call is in progress")),
527        Slot::Poisoned => {
528            *held = Slot::Poisoned;
529            Err(broken())
530        }
531    }
532}
533
534/// The stream of an idle session.
535fn into_stream(slot: Mutex<Slot>) -> Result<Box<Stream>> {
536    match slot.into_inner().unwrap_or_else(PoisonError::into_inner) {
537        Slot::Idle(stream) => Ok(stream),
538        Slot::Busy | Slot::Poisoned => Err(broken()),
539    }
540}
541
542/// The facts of the server from `reply`, the reply to a `Hello` with `refs`.
543///
544/// These replies are [`Error::Protocol`]:
545///
546/// - a version that is not the version of the session;
547/// - refs that are not `refs` in order.
548fn server_info(reply: HelloReply, refs: &[String]) -> Result<ServerInfo> {
549    if reply.version != PROTOCOL_VERSION {
550        return Err(protocol(format!(
551            "the server replied with protocol version {}, not {PROTOCOL_VERSION}",
552            reply.version
553        )));
554    }
555    if reply.refs.len() != refs.len() || reply.refs.iter().zip(refs).any(|(s, n)| s.name != *n) {
556        return Err(protocol("the refs of HelloReply are not the refs of Hello"));
557    }
558    Ok(ServerInfo {
559        version: reply.version,
560        mode: reply.mode,
561        collection_id: reply.collection_id,
562        max_frame: reply.max_frame,
563        max_have: reply.max_have,
564        encodings: reply.encodings,
565        parallel_uploads: reply.parallel_uploads,
566        refs: reply.refs,
567    })
568}
569
570/// The open of a session over a pair of byte streams, and its calls.
571impl PushSession {
572    /// Opens a session over a pair of byte streams.
573    ///
574    /// `input` comes from the server, and `output` goes to the server. The
575    /// session sends `Hello` with `refs`, the refs that it intends to update,
576    /// and reads `HelloReply`.
577    ///
578    /// The caller owns the liveness of the two streams. The session puts no
579    /// time limit on a read. A peer that stays silent keeps a call waiting
580    /// until the caller drops its future or closes the streams.
581    ///
582    /// A session over a stream uses the `futures-io` traits for its I/O, and
583    /// needs no async runtime, except for [`send`](PushSession::send) under
584    /// the `tokio` backend.
585    ///
586    /// # Errors
587    ///
588    /// - An `Error` message from the server, as the [`Error`] variant of its
589    ///   code, for example [`Error::VersionUnsupported`].
590    /// - [`Error::Protocol`] if the version of `HelloReply` is not the version
591    ///   of the session, or if its refs are not the refs of `Hello` in order.
592    /// - [`Error::Protocol`] for a malformed frame, or for a reply that is not
593    ///   `HelloReply`.
594    /// - [`Error::LimitExceeded`] for a frame over the frame limit.
595    /// - [`Error::Io`] for a failure of a stream. An end of `input` before
596    ///   the reply has the kind `UnexpectedEof`.
597    pub async fn over_stream<R, W>(
598        input: R,
599        output: W,
600        refs: &[String],
601        opts: SessionOptions,
602    ) -> Result<PushSession>
603    where
604        R: AsyncRead + Unpin + Send + 'static,
605        W: AsyncWrite + Unpin + Send + 'static,
606    {
607        PushSession::open(Box::new(input), Box::new(output), refs, opts, None).await
608    }
609
610    /// Opens a session over `input` and `output`. `pending_limit` bounds the
611    /// wait for a pending message after a failed write.
612    pub(crate) async fn open(
613        input: stream::Input,
614        output: stream::Output,
615        refs: &[String],
616        opts: SessionOptions,
617        pending_limit: Option<Duration>,
618    ) -> Result<PushSession> {
619        let counters = Arc::new(Counters::new(opts.progress.as_ref()));
620        counters.phase(PushPhase::Connecting);
621        let mut stream = Stream::new(input, output, Arc::clone(&counters));
622        if let Some(limit) = pending_limit {
623            stream.set_pending_limit(limit);
624        }
625        let agent = opts
626            .agent
627            .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
628        stream
629            .request(&Message::Hello(Hello {
630                version: PROTOCOL_VERSION,
631                agent: Some(agent),
632                refs: refs.to_vec(),
633                one_way: false,
634            }))
635            .await?;
636        let reply = match stream.next().await? {
637            Message::HelloReply(reply) => reply,
638            Message::Error(e) => return Err(e.into()),
639            other => return Err(unexpected(&other, "Hello")),
640        };
641        let server = server_info(reply, refs)?;
642        stream.set_write_limit(server.max_frame);
643        Ok(PushSession {
644            inner: SessionInner {
645                server,
646                counters,
647                claims: MetaClaims::default(),
648                link: Link::Stream {
649                    slot: Mutex::new(Slot::Idle(Box::new(stream))),
650                    transport: None,
651                },
652            },
653        })
654    }
655
656    /// Opens a session over HTTP at `endpoint`: sends `Hello` with `refs` and
657    /// reads `HelloReply`.
658    pub(crate) async fn open_http(
659        endpoint: Endpoint,
660        refs: &[String],
661        opts: SessionOptions,
662    ) -> Result<PushSession> {
663        let counters = Arc::new(Counters::new(opts.progress.as_ref()));
664        counters.phase(PushPhase::Connecting);
665        let agent = opts
666            .agent
667            .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
668        let (server, link) = http::open(endpoint, refs, agent, &counters).await?;
669        Ok(PushSession {
670            inner: SessionInner {
671                server,
672                counters,
673                claims: MetaClaims::default(),
674                link: Link::Http(link),
675            },
676        })
677    }
678
679    /// Attaches the child process the streams of the session belong to.
680    pub(crate) fn with_transport(mut self, child: Transport) -> PushSession {
681        if let Link::Stream { transport, .. } = &mut self.inner.link {
682            *transport = Some(child);
683        }
684        self
685    }
686
687    /// Returns the facts of the server.
688    pub fn server(&self) -> &ServerInfo {
689        &self.inner.server
690    }
691
692    /// Returns the objects of `names` that the server does not hold.
693    ///
694    /// The order of the result is the order of `names`. The session sends
695    /// `Have` messages of at most `max-have` names each. A `Have` also holds
696    /// no more names than its frame can hold within `max-frame`.
697    ///
698    /// Over HTTP, each `Have` is one request. The session sends the next
699    /// `Have` after the response to the one before it.
700    ///
701    /// # Errors
702    ///
703    /// - [`Error::InvalidInput`] if the type of a name is not a file, a
704    ///   dirtree, a dirmeta, or a commit. The call sends nothing, and the
705    ///   session stays usable.
706    /// - [`Error::InvalidInput`] if another call runs, as the rules of
707    ///   [concurrent calls](PushSession#concurrent-calls) state, or if the
708    ///   session is broken.
709    /// - An `Error` message from the server, as the [`Error`] variant of its
710    ///   code.
711    /// - [`Error::Protocol`] for a malformed reply, for a reply that is not
712    ///   `HaveReply`, or for a `HaveReply` whose length does not match its
713    ///   `Have`.
714    /// - [`Error::LimitExceeded`] on a stream transport, for a frame over the
715    ///   frame limit.
716    /// - [`Error::Io`] for a failure of the stream, or for a failed read of a
717    ///   response body over HTTP.
718    /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
719    /// - [`Error::Transport`] over HTTP, for a status other than 200, 401,
720    ///   403, 409, 422, 500, and 503, or for a body that is not one frame. A
721    ///   404 for a session that the server ended is such a status.
722    pub async fn missing(&self, names: &[ObjectName]) -> Result<Vec<ObjectName>> {
723        refuse_off_wire(names)?;
724        let slot = match &self.inner.link {
725            Link::Stream { slot, .. } => slot,
726            Link::Http(link) => {
727                return link
728                    .missing(&self.inner.server, &self.inner.counters, names)
729                    .await;
730            }
731        };
732        let mut taken = take(slot)?;
733        let counters = &self.inner.counters;
734        counters.phase(PushPhase::Negotiating);
735        counters.offered(names);
736        let stream = taken.stream();
737        let mut missing = Vec::new();
738        let server = &self.inner.server;
739        let batch_len = server
740            .max_have
741            .min(have_entries_within(server.max_frame))
742            .max(1);
743        for batch in names.chunks(batch_len as usize) {
744            stream.request(&Message::Have(batch.to_vec())).await?;
745            match stream.next().await? {
746                Message::HaveReply(reply) => {
747                    reply.check_len(batch.len())?;
748                    missing.extend(
749                        batch
750                            .iter()
751                            .enumerate()
752                            .filter(|(i, _)| reply.is_missing(*i))
753                            .map(|(_, n)| *n),
754                    );
755                }
756                Message::Error(e) => return Err(e.into()),
757                other => return Err(unexpected(&other, "Have")),
758            }
759        }
760        counters.needed(&missing);
761        taken.release();
762        Ok(missing)
763    }
764
765    /// Sends the objects `names` from `source`, then the detached metadata of
766    /// `commits`.
767    ///
768    /// On a stream transport, the objects go in one object stream. The call
769    /// sends the detached metadata of each commit in `commits` that has
770    /// detached metadata, if the session did not send it before. `commits`
771    /// holds the commits of `names` and the new value of each ref update, also
772    /// if `names` does not hold that commit. A call with nothing to send
773    /// writes nothing.
774    ///
775    /// If the session has a [`PushProgress`] and `names` holds at least one
776    /// file object, the call first asks [`ObjectSource::content_size`]. The
777    /// answer is the number of content bytes that the call sends.
778    ///
779    /// # HTTP
780    ///
781    /// Over HTTP, the call sends the objects in at most `parallel-uploads`
782    /// object streams at the same time, and in no more streams than the
783    /// objects that it sends. Each object stream is one request, and the
784    /// objects of `names` can arrive in another order. The detached metadata
785    /// goes in one of the streams, after its objects.
786    ///
787    /// The object streams of all the calls of the session stay within
788    /// `parallel-uploads`, at most 31. A stream waits for a permit. After the
789    /// first failure, no stream starts a new object, and each stream reads its
790    /// response.
791    ///
792    /// # Errors
793    ///
794    /// - [`Error::InvalidInput`] if the level of `compression` is not 1
795    ///   through 9, or if the type of a name is not a file, a dirtree, a
796    ///   dirmeta, or a commit. The call sends nothing, and the session stays
797    ///   usable.
798    /// - [`Error::InvalidInput`] if another call runs, as the rules of
799    ///   [concurrent calls](PushSession#concurrent-calls) state, or if the
800    ///   session is broken.
801    /// - [`Error::Source`] if the source fails. The session ends with
802    ///   `Abort`.
803    /// - [`Error::InvalidInput`] if the source gives data that the session
804    ///   cannot send, for example a symlink with a payload, or detached
805    ///   metadata that [`DetachedMetadata`] refuses. The session ends with
806    ///   `Abort`.
807    /// - An `Error` message from the server, as the [`Error`] variant of its
808    ///   code.
809    /// - [`Error::Protocol`] for a malformed reply, or for a reply that is
810    ///   not `ObjectsReply`.
811    /// - [`Error::LimitExceeded`] on a stream transport, for a frame over the
812    ///   frame limit.
813    /// - [`Error::Io`] for a failure of the stream, or for a failed read of a
814    ///   response body over HTTP.
815    /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
816    /// - [`Error::Transport`] over HTTP, for a status other than 200, 401,
817    ///   403, 409, 422, 500, and 503, or for a body that is not one frame. A
818    ///   404 for a session that the server ended is such a status.
819    ///
820    /// If more than one object stream fails over HTTP, the call returns one
821    /// error, in this order:
822    ///
823    /// 1. [`Error::Source`] or [`Error::InvalidInput`], a failure of the client
824    /// 2. an error with a wire code, for example an error that the server gave
825    ///    for its own cause
826    /// 3. any other error, also the [`Error::Protocol`] of a stream that ends
827    ///    because the server aborted the session for the failure of another
828    ///    stream
829    ///
830    /// # Panics
831    ///
832    /// Under the `tokio` backend, the call panics outside a tokio runtime
833    /// context if the source gives a [`DetachedMetadata::Dict`] for a commit
834    /// of `commits`. A session over ssh or HTTP also needs this context, as
835    /// [`connect`](PushSession::connect) states.
836    pub async fn send(
837        &self,
838        source: &dyn ObjectSource,
839        names: &[ObjectName],
840        commits: &[Checksum],
841        compression: Compression,
842    ) -> Result<()> {
843        let level = deflate_level(compression)?;
844        refuse_off_wire(names)?;
845        let deflate_ok = self.inner.server.encodings.contains(&Encoding::Deflate);
846        let level = level.filter(|_| deflate_ok);
847        let upload = Upload::new(
848            source,
849            names,
850            commits,
851            level,
852            deflate_ok,
853            &self.inner.claims,
854        );
855        let counters = &self.inner.counters;
856        let slot = match &self.inner.link {
857            Link::Stream { slot, .. } => slot,
858            Link::Http(link) => {
859                count_content_total(counters, source, names, level).await;
860                counters.phase(PushPhase::Uploading);
861                return link.send(counters, &upload).await;
862            }
863        };
864        let mut taken = take(slot)?;
865        count_content_total(counters, source, names, level).await;
866        counters.phase(PushPhase::Uploading);
867        taken.stream().upload(&upload).await?;
868        taken.release();
869        Ok(())
870    }
871
872    /// Sends `Commit` with `updates`, and returns the outcome from the reply.
873    ///
874    /// The call consumes the session. The call sends no `Commit` if it refuses
875    /// `updates`, if the session is broken, or if the `Commit` frame is over
876    /// the frame limit. On a stream transport it then sends nothing, so the
877    /// server reads the end of the stream. Over HTTP, it sends `DELETE`.
878    ///
879    /// Over ssh, the call then waits for the ssh client to exit, also after a
880    /// refusal. The ssh time limits of [`connect`](PushSession::connect) give
881    /// the rules of the wait.
882    ///
883    /// # HTTP
884    ///
885    /// The client sends the `Commit` request once, and never sends it again.
886    /// If the client did not hand the request over to a connection, the
887    /// server changed no ref. After the hand-over, these failures are
888    /// [`Error::CommitOutcomeUnknown`]:
889    ///
890    /// - a failure of the request
891    /// - a response head that the client refuses, for example for a declared
892    ///   coding or for a declared length over the cap
893    /// - a failed read of the response
894    /// - a status other than 200, 401, 403, 409, 422, 500, and 503, for
895    ///   example the 404 of a session that the server ended
896    /// - a body that is not one frame
897    ///
898    /// # Errors
899    ///
900    /// - [`Error::InvalidInput`] if `updates` is empty, names a ref that
901    ///   `Hello` did not name, or names a ref twice.
902    /// - [`Error::InvalidInput`] if the session is broken.
903    /// - [`Error::LimitExceeded`] if the `Commit` frame is over the frame
904    ///   limit.
905    /// - An `Error` message from the server, as the [`Error`] variant of its
906    ///   code. An ostrya server sends it before it changes a ref, with two
907    ///   exceptions. A failed write of the refs can leave some refs written,
908    ///   and a failure of a hook after the update keeps all the refs.
909    /// - [`Error::Fetch`] over HTTP, if the client did not hand the request
910    ///   over to a connection.
911    /// - [`Error::CommitOutcomeUnknown`] for each other end of the session
912    ///   after the session wrote `Commit`. The server can have written the
913    ///   refs. A `CommitReply` whose refs are not the refs of `updates` in
914    ///   order is one of these cases.
915    ///
916    /// If the write of `Commit` fails with an I/O error, the session reads one
917    /// message. An `Error` message gives the [`Error`] variant of its code,
918    /// and a `CommitReply` gives the outcome. Any other result is
919    /// [`Error::CommitOutcomeUnknown`].
920    pub async fn commit(self, updates: &[RefUpdate], force: bool) -> Result<PushOutcome> {
921        let checked = check_updates(&self.inner.server.refs, updates);
922        let request = CommitRequest {
923            updates: updates.to_vec(),
924            force,
925            server_commit: None,
926        };
927        let names = updates.iter().map(|u| u.name.clone()).collect();
928        // The future of the commit is large. The box keeps it out of the
929        // future of this call.
930        Box::pin(self.inner.send_commit(checked, request, names)).await
931    }
932
933    /// Checks the server commit `sc` against the session, and sends nothing.
934    ///
935    /// The check is the check of [`server_commit`](PushSession::server_commit)
936    /// before it sends `Commit`. A caller runs it after the session opens and
937    /// before it offers or sends an object, so that a refused server commit
938    /// sends no object.
939    ///
940    /// # Errors
941    ///
942    /// - [`Error::InvalidInput`] if `Hello` did not name the branch or a tag
943    ///   of `sc`, if a name is not a ref, or if `sc` names a ref twice among
944    ///   its branch and its tags. [`ServerInfo::canonical`] maps each name
945    ///   first, so `NAME` and `@OWN:NAME` name one ref, where `OWN` is the
946    ///   collection id of the server.
947    /// - [`Error::InvalidInput`] if the branch or a tag of `sc` is a local
948    ///   ref of the server whose name is 64 lowercase hex characters after
949    ///   that map: `NAME` or `@OWN:NAME`. A revision reads such a name as a
950    ///   commit checksum.
951    /// - [`Error::InvalidInput`] if the branch and the tags of `sc` are not
952    ///   in one namespace of the server after that map: the local refs, or
953    ///   the refs of one collection.
954    /// - [`Error::Protocol`] if the bytes of a metadata entry of `sc` are not
955    ///   a `v` in normal form.
956    /// - [`Error::InvalidInput`] if a commit cannot hold a metadata value of
957    ///   `sc`. A commit holds 128 levels of containers, counted from its
958    ///   metadata dict, so the value can hold two levels fewer than a `v`.
959    /// - [`Error::LimitExceeded`] if the `CommitReply` to `sc` can need a
960    ///   frame over the `max-frame` of the server. The longest reply holds
961    ///   the branch with an old and a new commit, and each tag with a new
962    ///   commit.
963    /// - [`Error::LimitExceeded`] if the `Commit` frame that holds `sc` is
964    ///   over the `max-frame` of the server.
965    pub fn check_server_commit(&self, sc: &ServerCommit) -> Result<()> {
966        check_server_commit_fields(&self.inner.server, sc)?;
967        let limit = self.inner.server.max_frame;
968        let len = server_commit_frame_len(sc)?;
969        if len > u64::from(limit) {
970            return Err(Error::LimitExceeded(format!(
971                "the Commit frame of the server commit is {len} bytes, over the limit {limit} \
972                 of the server"
973            )));
974        }
975        Ok(())
976    }
977
978    /// Sends `Commit` with the server commit `sc`, and returns the outcome
979    /// from the reply.
980    ///
981    /// The server makes a commit over the root dirtree and the root dirmeta
982    /// of `sc`. It moves the branch of `sc` to the commit and creates each
983    /// tag at it, in one transaction. [`PushOutcome::commit`] gives the new
984    /// commit, and [`PushOutcome::refs`] gives the outcome of the branch,
985    /// then of each tag.
986    ///
987    /// The call consumes the session. It sends no detached metadata. It
988    /// runs the checks of
989    /// [`check_server_commit`](PushSession::check_server_commit) before it
990    /// writes `Commit`. The encode of the `Commit` frame checks the length of
991    /// the frame, so the call encodes the frame one time. If a check fails,
992    /// or if the session is broken, the call sends no `Commit` and ends the
993    /// session as [`commit`](PushSession::commit) does. The rules of
994    /// the HTTP request and of the wait for the ssh client are those of
995    /// [`commit`](PushSession::commit).
996    ///
997    /// # Errors
998    ///
999    /// - Each error of
1000    ///   [`check_server_commit`](PushSession::check_server_commit).
1001    /// - [`Error::InvalidInput`] if the session is broken.
1002    /// - An `Error` message from the server, as the [`Error`] variant of its
1003    ///   code. An ostrya server sends it before it changes a ref. Examples
1004    ///   are [`Error::RefDenied`] for a client with no `c` on the branch, or
1005    ///   for a server whose hooks take no server commit, and
1006    ///   [`Error::RefMismatch`] for a tag that exists.
1007    /// - [`Error::Fetch`] over HTTP, if the client did not hand the request
1008    ///   over to a connection.
1009    /// - [`Error::CommitOutcomeUnknown`] for each other end of the session
1010    ///   after the session wrote `Commit`. The server can have written the
1011    ///   refs. A `CommitReply` that does not hold the branch and then each
1012    ///   tag, each at one new commit, with no old commit for a tag, is one of
1013    ///   these cases.
1014    pub async fn server_commit(self, sc: ServerCommit) -> Result<PushOutcome> {
1015        // The send path refuses a frame over the `max-frame` of the server
1016        // before it writes a byte.
1017        let checked = check_server_commit_fields(&self.inner.server, &sc);
1018        let names: Vec<String> = server_commit_refs(&sc).map(str::to_owned).collect();
1019        let request = CommitRequest {
1020            updates: Vec::new(),
1021            force: false,
1022            server_commit: Some(Box::new(sc)),
1023        };
1024        let mut outcome = Box::pin(self.inner.send_commit(checked, request, names)).await?;
1025        outcome.commit = Some(server_commit_checksum(&outcome.refs)?);
1026        Ok(outcome)
1027    }
1028
1029    /// Ends the session, so that the server aborts its transaction.
1030    ///
1031    /// On a stream transport, if the stream is usable, the session writes
1032    /// `Abort` and closes its output. A broken session has no stream, so the
1033    /// call writes nothing. Over ssh, the call then waits for the ssh client to
1034    /// exit, as the ssh time limits of [`connect`](PushSession::connect) state.
1035    ///
1036    /// Over HTTP, the call sends `DELETE`, also on a broken session. A 204 is
1037    /// success, and so is a 404, which the server gives for a session that it
1038    /// ended already.
1039    ///
1040    /// # Errors
1041    ///
1042    /// - [`Error::InvalidInput`] if the session is broken. Over HTTP, the
1043    ///   call sends `DELETE` first.
1044    /// - [`Error::Io`] if the write of `Abort` fails.
1045    /// - [`Error::Transport`] over ssh, if the write of `Abort` fails with an
1046    ///   I/O error and the ssh client exits with a failure status. The error
1047    ///   names the status.
1048    /// - An `Error` message from the server over HTTP, as the [`Error`]
1049    ///   variant of its code.
1050    /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
1051    /// - [`Error::Transport`] over HTTP, for a status that the endpoint does
1052    ///   not give, or for a body that is not one frame.
1053    /// - [`Error::Io`] over HTTP, for a failed read of the response body.
1054    pub async fn abort(self) -> Result<()> {
1055        let (slot, transport) = match self.inner.link {
1056            Link::Stream { slot, transport } => (slot, transport),
1057            Link::Http(link) => return link.abort().await,
1058        };
1059        let result = match into_stream(slot) {
1060            Ok(mut stream) => {
1061                let result = stream.write_raw(&Message::Abort).await;
1062                let _ = stream.close().await;
1063                result
1064            }
1065            Err(e) => Err(e),
1066        };
1067        finish(transport, result).await
1068    }
1069}
1070
1071/// A session that commits: the parts of a stream session, or the commit of
1072/// an HTTP session. The value lives for one match, so the size of the
1073/// stream variant costs nothing.
1074#[allow(clippy::large_enum_variant)]
1075enum Committing {
1076    Stream {
1077        slot: Mutex<Slot>,
1078        transport: Option<Transport>,
1079        counters: Arc<Counters>,
1080        checked: Result<()>,
1081        request: CommitRequest,
1082        names: Vec<String>,
1083    },
1084    /// The HTTP commit holds the response of its request, so its future is
1085    /// boxed, and the future of a stream commit does not hold it.
1086    Http(BoxFuture<'static, Result<PushOutcome>>),
1087}
1088
1089impl SessionInner {
1090    /// Takes the session apart to send `request`, which `checked` checked.
1091    /// `names` are the refs that the `CommitReply` must hold, in order.
1092    fn into_commit(
1093        self,
1094        checked: Result<()>,
1095        request: CommitRequest,
1096        names: Vec<String>,
1097    ) -> Committing {
1098        let SessionInner {
1099            server,
1100            counters,
1101            link,
1102            ..
1103        } = self;
1104        match link {
1105            Link::Stream { slot, transport } => Committing::Stream {
1106                slot,
1107                transport,
1108                counters,
1109                checked,
1110                request,
1111                names,
1112            },
1113            Link::Http(link) => Committing::Http(Box::pin(async move {
1114                link.commit(&server, &counters, checked, request, &names)
1115                    .await
1116            })),
1117        }
1118    }
1119
1120    /// Sends `Commit` with `request`, which `checked` checked, and returns
1121    /// the outcome from the reply. `names` are the refs that the
1122    /// `CommitReply` must hold, in order.
1123    async fn send_commit(
1124        self,
1125        checked: Result<()>,
1126        request: CommitRequest,
1127        names: Vec<String>,
1128    ) -> Result<PushOutcome> {
1129        let (slot, transport, counters, checked, request, names) =
1130            match self.into_commit(checked, request, names) {
1131                Committing::Stream {
1132                    slot,
1133                    transport,
1134                    counters,
1135                    checked,
1136                    request,
1137                    names,
1138                } => (slot, transport, counters, checked, request, names),
1139                Committing::Http(commit) => return commit.await,
1140            };
1141        let stream = into_stream(slot);
1142        let result = match (checked, stream) {
1143            (Ok(()), Ok(stream)) => commit_on(stream, request, &names, &counters).await,
1144            (Ok(()), Err(e)) => Err(e),
1145            (Err(e), stream) => {
1146                // The server reads the end of the stream.
1147                drop(stream);
1148                Err(e)
1149            }
1150        };
1151        finish(transport, result).await
1152    }
1153}
1154
1155/// Returns the refs that the server commit `sc` writes: the branch, then
1156/// each tag.
1157fn server_commit_refs(sc: &ServerCommit) -> impl Iterator<Item = &str> {
1158    std::iter::once(sc.branch.as_str()).chain(sc.tags.iter().map(String::as_str))
1159}
1160
1161/// Runs the checks of a server commit `sc` against the facts of `server`,
1162/// other than the length of the `Commit` frame: the names of the refs, the
1163/// checksum shape of each local ref of the server, and their namespace, the
1164/// depth of each metadata value, and the length of the longest
1165/// `CommitReply`.
1166fn check_server_commit_fields(server: &ServerInfo, sc: &ServerCommit) -> Result<()> {
1167    let named: HashSet<&str> = server.refs.iter().map(|r| r.name.as_str()).collect();
1168    let mut seen = HashSet::new();
1169    // The namespace of the first ref, and the ref: `None` for the local
1170    // refs of the server.
1171    let mut first: Option<(Option<String>, &str)> = None;
1172    for (i, name) in server_commit_refs(sc).enumerate() {
1173        if !named.contains(name) {
1174            return Err(invalid(format!(
1175                "ref '{name}' was not named when the session opened"
1176            )));
1177        }
1178        let r: Ref = name
1179            .parse()
1180            .map_err(|_| invalid(format!("'{name}' is not a valid ref name")))?;
1181        let r = r.canonical(server.collection_id.as_deref());
1182        let namespace = match &r {
1183            Ref::Collection { id, .. } => Some(id.clone()),
1184            Ref::Local { name: local } if ostrya_core::is_checksum_shaped(local) => {
1185                let what = if i == 0 { "branch" } else { "tag" };
1186                return Err(invalid(format!(
1187                    "{what} '{name}' is 64 hex characters, which a revision reads as a commit \
1188                     checksum"
1189                )));
1190            }
1191            _ => None,
1192        };
1193        if !seen.insert(r) {
1194            return Err(invalid(format!(
1195                "ref '{name}' is named twice in the server commit"
1196            )));
1197        }
1198        match &first {
1199            Some((ns, other)) if *ns != namespace => {
1200                return Err(invalid(format!(
1201                    "the refs '{other}' and '{name}' of the server commit are in two \
1202                     namespaces of the server"
1203                )));
1204            }
1205            Some(_) => {}
1206            None => first = Some((namespace, name)),
1207        }
1208    }
1209    check_server_commit_metadata(sc)?;
1210    let limit = server.max_frame;
1211    let len = server_commit_reply_frame_len(sc)?;
1212    if len > u64::from(limit) {
1213        return Err(Error::LimitExceeded(format!(
1214            "the reply to the server commit with {} tags can need a frame of {len} bytes, over \
1215             the limit {limit} of the server",
1216            sc.tags.len()
1217        )));
1218    }
1219    Ok(())
1220}
1221
1222/// Returns the commit of the `CommitReply` of a server commit, whose ref
1223/// names the session checked.
1224///
1225/// Each ref must have one new commit, and a tag must have no old commit.
1226/// Else the result is [`Error::CommitOutcomeUnknown`].
1227fn server_commit_checksum(refs: &[RefOutcome]) -> Result<Checksum> {
1228    let commit = refs.first().and_then(|branch| branch.new);
1229    match commit {
1230        Some(commit)
1231            if refs.iter().all(|r| r.new == Some(commit))
1232                && refs.iter().skip(1).all(|tag| tag.old.is_none()) =>
1233        {
1234            Ok(commit)
1235        }
1236        _ => Err(Error::CommitOutcomeUnknown {
1237            refs: refs.iter().map(|r| r.name.clone()).collect(),
1238            message: "the server replied to the server commit with refs that are not each at \
1239                      one new commit"
1240                .into(),
1241        }),
1242    }
1243}
1244
1245/// Refuses empty `updates`, a ref that is not in `refs`, and a ref named
1246/// twice.
1247fn check_updates(refs: &[RefState], updates: &[RefUpdate]) -> Result<()> {
1248    if updates.is_empty() {
1249        return Err(invalid("a commit needs at least one ref update"));
1250    }
1251    let mut seen = HashSet::new();
1252    for u in updates {
1253        if !refs.iter().any(|r| r.name == u.name) {
1254            return Err(invalid(format!(
1255                "ref '{}' was not named when the session opened",
1256                u.name
1257            )));
1258        }
1259        if !seen.insert(u.name.as_str()) {
1260            return Err(invalid(format!("ref '{}' is updated twice", u.name)));
1261        }
1262    }
1263    Ok(())
1264}
1265
1266/// Ends a session with `result`. A session with a transport waits for it to
1267/// finish. The stream of the session must be closed or dropped first.
1268async fn finish<T>(transport: Option<Transport>, result: Result<T>) -> Result<T> {
1269    match transport {
1270        Some(transport) => transport.finish(result).await,
1271        None => result,
1272    }
1273}
1274
1275/// Sends `Commit` with `request` over `stream` and reads the reply. The
1276/// reply must hold the refs `names`, in order. The stream is closed or
1277/// dropped when the call returns.
1278async fn commit_on(
1279    mut stream: Box<Stream>,
1280    request: CommitRequest,
1281    names: &[String],
1282    counters: &Counters,
1283) -> Result<PushOutcome> {
1284    counters.phase(PushPhase::Committing);
1285    let unknown = |message: String| Error::CommitOutcomeUnknown {
1286        refs: names.to_vec(),
1287        message,
1288    };
1289    let request = Message::Commit(request);
1290    let reply = match stream.write_raw(&request).await {
1291        Ok(()) => stream.read_raw().await,
1292        Err(e @ Error::Io(_)) => match stream.pending_message(&e).await {
1293            Some(msg @ (Message::Error(_) | Message::CommitReply(_))) => Ok(Some(msg)),
1294            _ => return Err(unknown(format!("the write of Commit failed: {e}"))),
1295        },
1296        Err(e) => return Err(e),
1297    };
1298    let refs = match reply {
1299        Ok(Some(Message::CommitReply(refs))) => refs,
1300        Ok(Some(Message::Error(e))) => return Err(e.into()),
1301        Ok(Some(other)) => {
1302            return Err(unknown(format!("{:?} in reply to Commit", other.kind())));
1303        }
1304        Ok(None) => return Err(unknown("the session ended before CommitReply".into())),
1305        Err(e) => return Err(unknown(format!("the reply to Commit failed: {e}"))),
1306    };
1307    if !reply_names_match(&refs, names) {
1308        return Err(unknown(
1309            "the server replied to Commit for other refs than the refs of Commit".into(),
1310        ));
1311    }
1312    // The refs are written. A failure to close the stream changes nothing.
1313    let _ = stream.close().await;
1314    Ok(PushOutcome {
1315        commit: None,
1316        refs,
1317        stats: counters.stats(),
1318    })
1319}
1320
1321/// Returns `true` if the outcomes `refs` of a `CommitReply` name the refs
1322/// `names`, in order.
1323fn reply_names_match(refs: &[RefOutcome], names: &[String]) -> bool {
1324    refs.len() == names.len() && refs.iter().zip(names).all(|(o, n)| o.name == *n)
1325}