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