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};
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 pub collection_id: Option<String>,
290 /// The collection of the namespace of the session, from the key
291 /// `collection` of `HelloReply`.
292 ///
293 /// `None` is the local refs of the server. The session checks the value
294 /// against [`SessionOptions::collection`] when it opens. With no
295 /// requested collection, the value is `None`. With a requested id, the
296 /// value is that id, or `None` if the id is
297 /// [`collection_id`](ServerInfo::collection_id).
298 pub collection: Option<String>,
299 /// The frame and chunk limit that the session writes with.
300 ///
301 /// The value is in
302 /// [`MIN_FRAME_LIMIT`](crate::proto::MIN_FRAME_LIMIT)`..=`[`MAX_FRAME_LIMIT`](crate::proto::MAX_FRAME_LIMIT).
303 pub max_frame: u32,
304 /// The highest number of object names in one `Have`.
305 pub max_have: u32,
306 /// The content encodings that the server accepts.
307 pub encodings: Vec<Encoding>,
308 /// The most object streams that the server serves at the same time.
309 pub parallel_uploads: u32,
310 /// The state of each ref that the session named, in the order of the names.
311 pub refs: Vec<RefState>,
312}
313
314impl ServerInfo {
315 /// Returns the collection id that a commit of the session binds to.
316 ///
317 /// The value is [`collection`](ServerInfo::collection) for a collection
318 /// namespace, and [`collection_id`](ServerInfo::collection_id) for the
319 /// local refs. `None` is the local refs of a server with no collection
320 /// id.
321 pub fn binding_collection(&self) -> Option<&str> {
322 self.collection.as_deref().or(self.collection_id.as_deref())
323 }
324
325 /// Returns the current commit of the ref `name` on the server.
326 ///
327 /// Returns `None` if the ref is absent, or if the session did not name it.
328 pub fn tip(&self, name: &str) -> Option<Checksum> {
329 self.refs
330 .iter()
331 .find(|r| r.name == name)
332 .and_then(|r| r.commit)
333 }
334}
335
336/// The options of a session.
337#[derive(Debug, Clone, Default)]
338pub struct SessionOptions {
339 /// The `agent` that the session sends in `Hello`.
340 ///
341 /// The default is `ostrya/<version>`.
342 pub agent: Option<String>,
343 /// The collection id that the session sends in `Hello`, under the key
344 /// `collection`.
345 ///
346 /// `None` targets the local refs of the server. The collection id of the
347 /// server also targets its local refs. The session does not check the
348 /// id: the server refuses an id that fails the collection-id rule.
349 pub collection: Option<String>,
350 /// A handle that the session also counts its progress into.
351 pub progress: Option<PushProgress>,
352}
353
354/// The result of a push that committed.
355#[derive(Debug, Clone, PartialEq, Eq)]
356pub struct PushOutcome {
357 /// The commit that the server made for
358 /// [`server_commit`](PushSession::server_commit).
359 ///
360 /// A session that ends with [`commit`](PushSession::commit) gives
361 /// `None`.
362 pub commit: Option<Checksum>,
363 /// One outcome for each ref update, in the order of the updates.
364 pub refs: Vec<RefOutcome>,
365 /// The statistics of the session.
366 pub stats: PushStats,
367}
368
369/// A client session of a push, over a stream transport or over HTTP.
370///
371/// [`connect`](PushSession::connect) opens a session over ssh or HTTP, and
372/// [`prepare`](PushSession::prepare) checks the transport before the open.
373/// [`over_stream`](PushSession::over_stream) opens a session over a pair of
374/// byte streams.
375///
376/// If the caller drops a session without [`commit`](PushSession::commit),
377/// [`server_commit`](PushSession::server_commit), or
378/// [`abort`](PushSession::abort), the session sends nothing more. A stream
379/// transport then closes its output, so the server reads the end of the
380/// stream. Over HTTP, the server ends the session when its idle timeout ends.
381///
382/// After the server ends a session over HTTP, it answers each later request
383/// of that session with 404. The session reports a 404 on
384/// [`missing`](PushSession::missing) or [`send`](PushSession::send) as
385/// [`Error::Transport`], and a 404 on [`commit`](PushSession::commit) or
386/// [`server_commit`](PushSession::server_commit) as
387/// [`Error::CommitOutcomeUnknown`].
388///
389/// # Verification
390///
391/// The session does not verify the objects that it sends. It computes no
392/// checksum and checks no size. The server verifies each object when it
393/// arrives. If a source fails while the session sends an object, the session
394/// abandons the object with the abandon marker and ends the session with
395/// `Abort`.
396///
397/// # Concurrent calls
398///
399/// The session is `Send + Sync`. On a stream transport, the session runs one
400/// call at a time. A call to [`missing`](PushSession::missing) or
401/// [`send`](PushSession::send) while another call runs fails at once with
402/// [`Error::InvalidInput`].
403///
404/// Over HTTP, several [`send`](PushSession::send) calls can run at the same
405/// time, and a [`missing`](PushSession::missing) call can run beside them. A
406/// second `missing` call while one runs fails at once with
407/// [`Error::InvalidInput`].
408///
409/// On both transports, a call that fails, or whose future the caller drops
410/// before it completes, leaves the session broken. Each later call then fails
411/// with [`Error::InvalidInput`]. If `missing` or `send` refuses an argument,
412/// the call sends nothing and the session stays usable.
413pub struct PushSession {
414 inner: SessionInner,
415}
416
417struct SessionInner {
418 server: ServerInfo,
419 counters: Arc<Counters>,
420 /// The claims of the detached metadata the session sends.
421 claims: MetaClaims,
422 link: Link,
423}
424
425/// The transport of a session.
426enum Link {
427 /// A pair of byte streams.
428 Stream {
429 slot: Mutex<Slot>,
430 /// The child process the streams belong to, for a session that
431 /// [`PushSession::connect`] opened.
432 transport: Option<Transport>,
433 },
434 /// The receive endpoint of an HTTP server.
435 Http(HttpLink),
436}
437
438enum Slot {
439 /// No call runs.
440 Idle(Box<Stream>),
441 /// A call runs and holds the stream.
442 Busy,
443 /// A call failed or was dropped. The stream is gone.
444 Poisoned,
445}
446
447/// The stream a call holds. The call gives it back with
448/// [`release`](Taken::release) when it completes. Dropped without a release,
449/// it leaves the session broken.
450struct Taken<'a> {
451 slot: &'a Mutex<Slot>,
452 stream: Option<Box<Stream>>,
453}
454
455impl Taken<'_> {
456 fn stream(&mut self) -> &mut Stream {
457 self.stream.as_mut().expect("the stream is held")
458 }
459
460 fn release(mut self) {
461 let stream = self.stream.take().expect("the stream is held");
462 *self.slot.lock().unwrap_or_else(PoisonError::into_inner) = Slot::Idle(stream);
463 }
464}
465
466impl Drop for Taken<'_> {
467 fn drop(&mut self) {
468 if self.stream.is_some() {
469 *self.slot.lock().unwrap_or_else(PoisonError::into_inner) = Slot::Poisoned;
470 }
471 }
472}
473
474pub(crate) fn invalid(msg: impl Into<String>) -> Error {
475 Error::InvalidInput(msg.into())
476}
477
478pub(super) fn broken() -> Error {
479 invalid("the session is broken")
480}
481
482pub(super) fn unexpected(msg: &Message, request: &str) -> Error {
483 protocol(format!("{:?} in reply to {request}", msg.kind()))
484}
485
486/// The DEFLATE level of `compression`, or `None` for `raw`. A level outside 1
487/// through 9 is [`Error::InvalidInput`].
488pub(crate) fn deflate_level(compression: Compression) -> Result<Option<u8>> {
489 match compression {
490 Compression::None => Ok(None),
491 Compression::Deflate { level } if (1..=9).contains(&level) => Ok(Some(level)),
492 Compression::Deflate { level } => Err(invalid(format!(
493 "compression level {level} is not in 1 through 9"
494 ))),
495 }
496}
497
498/// Asks `source` for the content bytes of the file objects of `names`, sent
499/// at `level`, and adds them to the byte total of `counters`. A session with
500/// no caller's handle, and names with no file object, ask nothing. An
501/// unknown size and a failure add nothing.
502async fn count_content_total(
503 counters: &Counters,
504 source: &dyn ObjectSource,
505 names: &[ObjectName],
506 level: Option<u8>,
507) {
508 if !counters.has_caller() || !names.iter().any(|n| n.ty == ObjectType::File) {
509 return;
510 }
511 let encoding = match level {
512 Some(_) => Encoding::Deflate,
513 None => Encoding::Raw,
514 };
515 if let Ok(Some(total)) = source.content_size(names, encoding).await {
516 counters.content_total(total);
517 }
518}
519
520/// Refuses a name of a type that `Have` and the objects of a source cannot
521/// carry. The session sends detached metadata for a commit on its own.
522fn refuse_off_wire(names: &[ObjectName]) -> Result<()> {
523 match names.iter().find(|n| !have_type(n.ty)) {
524 Some(n) => Err(invalid(format!(
525 "object {} of type {:?} is not an object to offer or send",
526 n.checksum, n.ty
527 ))),
528 None => Ok(()),
529 }
530}
531
532/// Takes the stream of `slot` for one call.
533fn take(slot: &Mutex<Slot>) -> Result<Taken<'_>> {
534 let mut held = slot.lock().unwrap_or_else(PoisonError::into_inner);
535 match std::mem::replace(&mut *held, Slot::Busy) {
536 Slot::Idle(stream) => Ok(Taken {
537 slot,
538 stream: Some(stream),
539 }),
540 Slot::Busy => Err(invalid("a call is in progress")),
541 Slot::Poisoned => {
542 *held = Slot::Poisoned;
543 Err(broken())
544 }
545 }
546}
547
548/// The stream of an idle session.
549fn into_stream(slot: Mutex<Slot>) -> Result<Box<Stream>> {
550 match slot.into_inner().unwrap_or_else(PoisonError::into_inner) {
551 Slot::Idle(stream) => Ok(stream),
552 Slot::Busy | Slot::Poisoned => Err(broken()),
553 }
554}
555
556/// The facts of the server from `reply`, the reply to a `Hello` with `refs`
557/// and `collection`.
558///
559/// These replies are [`Error::Protocol`]:
560///
561/// - a version that is not the version of the session;
562/// - refs that are not `refs` in order;
563/// - a `collection` that does not match the request. A request with no
564/// collection needs a reply with none. A request of an id needs a reply of
565/// that id, or a reply with none from a server whose collection id is that
566/// id.
567fn server_info(reply: HelloReply, refs: &[String], collection: Option<&str>) -> Result<ServerInfo> {
568 if reply.version != PROTOCOL_VERSION {
569 return Err(protocol(format!(
570 "the server replied with protocol version {}, not {PROTOCOL_VERSION}",
571 reply.version
572 )));
573 }
574 if reply.refs.len() != refs.len() || reply.refs.iter().zip(refs).any(|(s, n)| s.name != *n) {
575 return Err(protocol("the refs of HelloReply are not the refs of Hello"));
576 }
577 let matches = match (collection, reply.collection.as_deref()) {
578 (None, None) => true,
579 (Some(asked), Some(got)) => asked == got,
580 (Some(asked), None) => reply.collection_id.as_deref() == Some(asked),
581 (None, Some(_)) => false,
582 };
583 if !matches {
584 let text = |c: Option<&str>| c.map_or_else(|| "none".to_owned(), |id| format!("'{id}'"));
585 return Err(protocol(format!(
586 "the collection {} of HelloReply does not match the collection {} of Hello",
587 text(reply.collection.as_deref()),
588 text(collection)
589 )));
590 }
591 Ok(ServerInfo {
592 version: reply.version,
593 mode: reply.mode,
594 collection_id: reply.collection_id,
595 collection: reply.collection,
596 max_frame: reply.max_frame,
597 max_have: reply.max_have,
598 encodings: reply.encodings,
599 parallel_uploads: reply.parallel_uploads,
600 refs: reply.refs,
601 })
602}
603
604/// The open of a session over a pair of byte streams, and its calls.
605impl PushSession {
606 /// Opens a session over a pair of byte streams.
607 ///
608 /// `input` comes from the server, and `output` goes to the server. The
609 /// session sends `Hello` with `refs`, the refs that it intends to update,
610 /// and reads `HelloReply`.
611 ///
612 /// The caller owns the liveness of the two streams. The session puts no
613 /// time limit on a read. A peer that stays silent keeps a call waiting
614 /// until the caller drops its future or closes the streams.
615 ///
616 /// A session over a stream uses the `futures-io` traits for its I/O, and
617 /// needs no async runtime, except for [`send`](PushSession::send) under
618 /// the `tokio` backend.
619 ///
620 /// # Errors
621 ///
622 /// - An `Error` message from the server, as the [`Error`] variant of its
623 /// code, for example [`Error::VersionUnsupported`].
624 /// - [`Error::Protocol`] if the version of `HelloReply` is not the version
625 /// of the session, or if its refs are not the refs of `Hello` in order.
626 /// - [`Error::Protocol`] if the `collection` of `HelloReply` does not
627 /// match [`SessionOptions::collection`]. [`ServerInfo::collection`]
628 /// states the match.
629 /// - [`Error::Protocol`] for a malformed frame, or for a reply that is not
630 /// `HelloReply`.
631 /// - [`Error::LimitExceeded`] for a frame over the frame limit.
632 /// - [`Error::Io`] for a failure of a stream. An end of `input` before
633 /// the reply has the kind `UnexpectedEof`.
634 pub async fn over_stream<R, W>(
635 input: R,
636 output: W,
637 refs: &[String],
638 opts: SessionOptions,
639 ) -> Result<PushSession>
640 where
641 R: AsyncRead + Unpin + Send + 'static,
642 W: AsyncWrite + Unpin + Send + 'static,
643 {
644 PushSession::open(Box::new(input), Box::new(output), refs, opts, None).await
645 }
646
647 /// Opens a session over `input` and `output`. `pending_limit` bounds the
648 /// wait for a pending message after a failed write.
649 pub(crate) async fn open(
650 input: stream::Input,
651 output: stream::Output,
652 refs: &[String],
653 opts: SessionOptions,
654 pending_limit: Option<Duration>,
655 ) -> Result<PushSession> {
656 let counters = Arc::new(Counters::new(opts.progress.as_ref()));
657 counters.phase(PushPhase::Connecting);
658 let mut stream = Stream::new(input, output, Arc::clone(&counters));
659 if let Some(limit) = pending_limit {
660 stream.set_pending_limit(limit);
661 }
662 let agent = opts
663 .agent
664 .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
665 stream
666 .request(&Message::Hello(Hello {
667 version: PROTOCOL_VERSION,
668 agent: Some(agent),
669 refs: refs.to_vec(),
670 collection: opts.collection.clone(),
671 one_way: false,
672 }))
673 .await?;
674 let reply = match stream.next().await? {
675 Message::HelloReply(reply) => reply,
676 Message::Error(e) => return Err(e.into()),
677 other => return Err(unexpected(&other, "Hello")),
678 };
679 let server = server_info(reply, refs, opts.collection.as_deref())?;
680 stream.set_write_limit(server.max_frame);
681 Ok(PushSession {
682 inner: SessionInner {
683 server,
684 counters,
685 claims: MetaClaims::default(),
686 link: Link::Stream {
687 slot: Mutex::new(Slot::Idle(Box::new(stream))),
688 transport: None,
689 },
690 },
691 })
692 }
693
694 /// Opens a session over HTTP at `endpoint`: sends `Hello` with `refs` and
695 /// reads `HelloReply`.
696 pub(crate) async fn open_http(
697 endpoint: Endpoint,
698 refs: &[String],
699 opts: SessionOptions,
700 ) -> Result<PushSession> {
701 let counters = Arc::new(Counters::new(opts.progress.as_ref()));
702 counters.phase(PushPhase::Connecting);
703 let agent = opts
704 .agent
705 .unwrap_or_else(|| format!("ostrya/{}", env!("CARGO_PKG_VERSION")));
706 let (server, link) = http::open(endpoint, refs, agent, opts.collection, &counters).await?;
707 Ok(PushSession {
708 inner: SessionInner {
709 server,
710 counters,
711 claims: MetaClaims::default(),
712 link: Link::Http(link),
713 },
714 })
715 }
716
717 /// Attaches the child process the streams of the session belong to.
718 pub(crate) fn with_transport(mut self, child: Transport) -> PushSession {
719 if let Link::Stream { transport, .. } = &mut self.inner.link {
720 *transport = Some(child);
721 }
722 self
723 }
724
725 /// Returns the facts of the server.
726 pub fn server(&self) -> &ServerInfo {
727 &self.inner.server
728 }
729
730 /// Returns the objects of `names` that the server does not hold.
731 ///
732 /// The order of the result is the order of `names`. The session sends
733 /// `Have` messages of at most `max-have` names each. A `Have` also holds
734 /// no more names than its frame can hold within `max-frame`.
735 ///
736 /// Over HTTP, each `Have` is one request. The session sends the next
737 /// `Have` after the response to the one before it.
738 ///
739 /// # Errors
740 ///
741 /// - [`Error::InvalidInput`] if the type of a name is not a file, a
742 /// dirtree, a dirmeta, or a commit. The call sends nothing, and the
743 /// session stays usable.
744 /// - [`Error::InvalidInput`] if another call runs, as the rules of
745 /// [concurrent calls](PushSession#concurrent-calls) state, or if the
746 /// session is broken.
747 /// - An `Error` message from the server, as the [`Error`] variant of its
748 /// code.
749 /// - [`Error::Protocol`] for a malformed reply, for a reply that is not
750 /// `HaveReply`, or for a `HaveReply` whose length does not match its
751 /// `Have`.
752 /// - [`Error::LimitExceeded`] on a stream transport, for a frame over the
753 /// frame limit.
754 /// - [`Error::Io`] for a failure of the stream, or for a failed read of a
755 /// response body over HTTP.
756 /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
757 /// - [`Error::Transport`] over HTTP, for a status other than 200, 401,
758 /// 403, 409, 422, 500, and 503, or for a body that is not one frame. A
759 /// 404 for a session that the server ended is such a status.
760 pub async fn missing(&self, names: &[ObjectName]) -> Result<Vec<ObjectName>> {
761 refuse_off_wire(names)?;
762 let slot = match &self.inner.link {
763 Link::Stream { slot, .. } => slot,
764 Link::Http(link) => {
765 return link
766 .missing(&self.inner.server, &self.inner.counters, names)
767 .await;
768 }
769 };
770 let mut taken = take(slot)?;
771 let counters = &self.inner.counters;
772 counters.phase(PushPhase::Negotiating);
773 counters.offered(names.len() as u64);
774 let stream = taken.stream();
775 let mut missing = Vec::new();
776 let server = &self.inner.server;
777 let batch_len = server
778 .max_have
779 .min(have_entries_within(server.max_frame))
780 .max(1);
781 for batch in names.chunks(batch_len as usize) {
782 stream.request(&Message::Have(batch.to_vec())).await?;
783 match stream.next().await? {
784 Message::HaveReply(reply) => {
785 reply.check_len(batch.len())?;
786 missing.extend(
787 batch
788 .iter()
789 .enumerate()
790 .filter(|(i, _)| reply.is_missing(*i))
791 .map(|(_, n)| *n),
792 );
793 }
794 Message::Error(e) => return Err(e.into()),
795 other => return Err(unexpected(&other, "Have")),
796 }
797 }
798 counters.needed(missing.len() as u64);
799 taken.release();
800 Ok(missing)
801 }
802
803 /// Sends the objects `names` from `source`, then the detached metadata of
804 /// `commits`.
805 ///
806 /// On a stream transport, the objects go in one object stream. The call
807 /// sends the detached metadata of each commit in `commits` that has
808 /// detached metadata, if the session did not send it before. `commits`
809 /// holds the commits of `names` and the new value of each ref update, also
810 /// if `names` does not hold that commit. A call with nothing to send
811 /// writes nothing.
812 ///
813 /// If the session has a [`PushProgress`] and `names` holds at least one
814 /// file object, the call first asks [`ObjectSource::content_size`]. The
815 /// answer is the number of content bytes that the call sends.
816 ///
817 /// # HTTP
818 ///
819 /// Over HTTP, the call sends the objects in at most `parallel-uploads`
820 /// object streams at the same time, and in no more streams than the
821 /// objects that it sends. Each object stream is one request, and the
822 /// objects of `names` can arrive in another order. The detached metadata
823 /// goes in one of the streams, after its objects.
824 ///
825 /// The object streams of all the calls of the session stay within
826 /// `parallel-uploads`, at most 31. A stream waits for a permit. After the
827 /// first failure, no stream starts a new object, and each stream reads its
828 /// response.
829 ///
830 /// # Errors
831 ///
832 /// - [`Error::InvalidInput`] if the level of `compression` is not 1
833 /// through 9, or if the type of a name is not a file, a dirtree, a
834 /// dirmeta, or a commit. The call sends nothing, and the session stays
835 /// usable.
836 /// - [`Error::InvalidInput`] if another call runs, as the rules of
837 /// [concurrent calls](PushSession#concurrent-calls) state, or if the
838 /// session is broken.
839 /// - [`Error::Source`] if the source fails. The session ends with
840 /// `Abort`.
841 /// - [`Error::InvalidInput`] if the source gives data that the session
842 /// cannot send, for example a symlink with a payload, or detached
843 /// metadata that [`DetachedMetadata`] refuses. The session ends with
844 /// `Abort`.
845 /// - An `Error` message from the server, as the [`Error`] variant of its
846 /// code.
847 /// - [`Error::Protocol`] for a malformed reply, or for a reply that is
848 /// not `ObjectsReply`.
849 /// - [`Error::LimitExceeded`] on a stream transport, for a frame over the
850 /// frame limit.
851 /// - [`Error::Io`] for a failure of the stream, or for a failed read of a
852 /// response body over HTTP.
853 /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
854 /// - [`Error::Transport`] over HTTP, for a status other than 200, 401,
855 /// 403, 409, 422, 500, and 503, or for a body that is not one frame. A
856 /// 404 for a session that the server ended is such a status.
857 ///
858 /// If more than one object stream fails over HTTP, the call returns one
859 /// error, in this order:
860 ///
861 /// 1. [`Error::Source`] or [`Error::InvalidInput`], a failure of the client
862 /// 2. an error with a wire code, for example an error that the server gave
863 /// for its own cause
864 /// 3. any other error, also the [`Error::Protocol`] of a stream that ends
865 /// because the server aborted the session for the failure of another
866 /// stream
867 ///
868 /// # Panics
869 ///
870 /// Under the `tokio` backend, the call panics outside a tokio runtime
871 /// context if the source gives a [`DetachedMetadata::Dict`] for a commit
872 /// of `commits`. A session over ssh or HTTP also needs this context, as
873 /// [`connect`](PushSession::connect) states.
874 pub async fn send(
875 &self,
876 source: &dyn ObjectSource,
877 names: &[ObjectName],
878 commits: &[Checksum],
879 compression: Compression,
880 ) -> Result<()> {
881 let level = deflate_level(compression)?;
882 refuse_off_wire(names)?;
883 let deflate_ok = self.inner.server.encodings.contains(&Encoding::Deflate);
884 let level = level.filter(|_| deflate_ok);
885 let upload = Upload::new(
886 source,
887 names,
888 commits,
889 level,
890 deflate_ok,
891 &self.inner.claims,
892 );
893 let counters = &self.inner.counters;
894 let slot = match &self.inner.link {
895 Link::Stream { slot, .. } => slot,
896 Link::Http(link) => {
897 count_content_total(counters, source, names, level).await;
898 counters.phase(PushPhase::Uploading);
899 return link.send(counters, &upload).await;
900 }
901 };
902 let mut taken = take(slot)?;
903 count_content_total(counters, source, names, level).await;
904 counters.phase(PushPhase::Uploading);
905 taken.stream().upload(&upload).await?;
906 taken.release();
907 Ok(())
908 }
909
910 /// Sends `Commit` with `updates`, and returns the outcome from the reply.
911 ///
912 /// The call consumes the session. The call sends no `Commit` if it refuses
913 /// `updates`, if the session is broken, or if the `Commit` frame is over
914 /// the frame limit. On a stream transport it then sends nothing, so the
915 /// server reads the end of the stream. Over HTTP, it sends `DELETE`.
916 ///
917 /// Over ssh, the call then waits for the ssh client to exit, also after a
918 /// refusal. The ssh time limits of [`connect`](PushSession::connect) give
919 /// the rules of the wait.
920 ///
921 /// # HTTP
922 ///
923 /// The client sends the `Commit` request once, and never sends it again.
924 /// If the client did not hand the request over to a connection, the
925 /// server changed no ref. After the hand-over, these failures are
926 /// [`Error::CommitOutcomeUnknown`]:
927 ///
928 /// - a failure of the request
929 /// - a response head that the client refuses, for example for a declared
930 /// coding or for a declared length over the cap
931 /// - a failed read of the response
932 /// - a status other than 200, 401, 403, 409, 422, 500, and 503, for
933 /// example the 404 of a session that the server ended
934 /// - a body that is not one frame
935 ///
936 /// # Errors
937 ///
938 /// - [`Error::InvalidInput`] if `updates` is empty, names a ref that
939 /// `Hello` did not name, or names a ref twice.
940 /// - [`Error::InvalidInput`] if the session is broken.
941 /// - [`Error::LimitExceeded`] if the `Commit` frame is over the frame
942 /// limit.
943 /// - An `Error` message from the server, as the [`Error`] variant of its
944 /// code. An ostrya server sends it before it changes a ref, with two
945 /// exceptions. A failed write of the refs can leave some refs written,
946 /// and a failure of a hook after the update keeps all the refs.
947 /// - [`Error::Fetch`] over HTTP, if the client did not hand the request
948 /// over to a connection.
949 /// - [`Error::CommitOutcomeUnknown`] for each other end of the session
950 /// after the session wrote `Commit`. The server can have written the
951 /// refs. A `CommitReply` whose refs are not the refs of `updates` in
952 /// order is one of these cases.
953 ///
954 /// If the write of `Commit` fails with an I/O error, the session reads one
955 /// message. An `Error` message gives the [`Error`] variant of its code,
956 /// and a `CommitReply` gives the outcome. Any other result is
957 /// [`Error::CommitOutcomeUnknown`].
958 pub async fn commit(self, updates: &[RefUpdate], force: bool) -> Result<PushOutcome> {
959 let checked = check_updates(&self.inner.server.refs, updates);
960 let request = CommitRequest {
961 updates: updates.to_vec(),
962 force,
963 server_commit: None,
964 };
965 let names = updates.iter().map(|u| u.name.clone()).collect();
966 // The future of the commit is large. The box keeps it out of the
967 // future of this call.
968 Box::pin(self.inner.send_commit(checked, request, names)).await
969 }
970
971 /// Checks the server commit `sc` against the session, and sends nothing.
972 ///
973 /// The check is the check of [`server_commit`](PushSession::server_commit)
974 /// before it sends `Commit`. A caller runs it after the session opens and
975 /// before it offers or sends an object, so that a refused server commit
976 /// sends no object.
977 ///
978 /// # Errors
979 ///
980 /// - [`Error::InvalidInput`] if `Hello` did not name the branch or a tag
981 /// of `sc`, or if `sc` names a ref twice among its branch and its
982 /// tags.
983 /// - [`Error::Protocol`] if the bytes of a metadata entry of `sc` are not
984 /// a `v` in normal form.
985 /// - [`Error::InvalidInput`] if a commit cannot hold a metadata value of
986 /// `sc`. A commit holds 128 levels of containers, counted from its
987 /// metadata dict, so the value can hold two levels fewer than a `v`.
988 /// - [`Error::LimitExceeded`] if the `CommitReply` to `sc` can need a
989 /// frame over the `max-frame` of the server. The longest reply holds
990 /// the branch with an old and a new commit, and each tag with a new
991 /// commit.
992 /// - [`Error::LimitExceeded`] if the `Commit` frame that holds `sc` is
993 /// over the `max-frame` of the server.
994 pub fn check_server_commit(&self, sc: &ServerCommit) -> Result<()> {
995 check_server_commit_fields(&self.inner.server, sc)?;
996 let limit = self.inner.server.max_frame;
997 let len = server_commit_frame_len(sc)?;
998 if len > u64::from(limit) {
999 return Err(Error::LimitExceeded(format!(
1000 "the Commit frame of the server commit is {len} bytes, over the limit {limit} \
1001 of the server"
1002 )));
1003 }
1004 Ok(())
1005 }
1006
1007 /// Sends `Commit` with the server commit `sc`, and returns the outcome
1008 /// from the reply.
1009 ///
1010 /// The server makes a commit over the root dirtree and the root dirmeta
1011 /// of `sc`. It moves the branch of `sc` to the commit and creates each
1012 /// tag at it, in one transaction. [`PushOutcome::commit`] gives the new
1013 /// commit, and [`PushOutcome::refs`] gives the outcome of the branch,
1014 /// then of each tag.
1015 ///
1016 /// The call consumes the session. It sends no detached metadata. It
1017 /// runs the checks of
1018 /// [`check_server_commit`](PushSession::check_server_commit) before it
1019 /// writes `Commit`. The encode of the `Commit` frame checks the length of
1020 /// the frame, so the call encodes the frame one time. If a check fails,
1021 /// or if the session is broken, the call sends no `Commit` and ends the
1022 /// session as [`commit`](PushSession::commit) does. The rules of
1023 /// the HTTP request and of the wait for the ssh client are those of
1024 /// [`commit`](PushSession::commit).
1025 ///
1026 /// # Errors
1027 ///
1028 /// - Each error of
1029 /// [`check_server_commit`](PushSession::check_server_commit).
1030 /// - [`Error::InvalidInput`] if the session is broken.
1031 /// - An `Error` message from the server, as the [`Error`] variant of its
1032 /// code. An ostrya server sends it before it changes a ref. Examples
1033 /// are [`Error::RefDenied`] for a client with no `c` on the branch, or
1034 /// for a server that runs hooks, and [`Error::RefMismatch`] for a tag
1035 /// that exists.
1036 /// - [`Error::Fetch`] over HTTP, if the client did not hand the request
1037 /// over to a connection.
1038 /// - [`Error::CommitOutcomeUnknown`] for each other end of the session
1039 /// after the session wrote `Commit`. The server can have written the
1040 /// refs. A `CommitReply` that does not hold the branch and then each
1041 /// tag, each at one new commit, with no old commit for a tag, is one of
1042 /// these cases.
1043 pub async fn server_commit(self, sc: ServerCommit) -> Result<PushOutcome> {
1044 // The send path refuses a frame over the `max-frame` of the server
1045 // before it writes a byte.
1046 let checked = check_server_commit_fields(&self.inner.server, &sc);
1047 let names: Vec<String> = server_commit_refs(&sc).map(str::to_owned).collect();
1048 let request = CommitRequest {
1049 updates: Vec::new(),
1050 force: false,
1051 server_commit: Some(Box::new(sc)),
1052 };
1053 let mut outcome = Box::pin(self.inner.send_commit(checked, request, names)).await?;
1054 outcome.commit = Some(server_commit_checksum(&outcome.refs)?);
1055 Ok(outcome)
1056 }
1057
1058 /// Ends the session, so that the server aborts its transaction.
1059 ///
1060 /// On a stream transport, if the stream is usable, the session writes
1061 /// `Abort` and closes its output. A broken session has no stream, so the
1062 /// call writes nothing. Over ssh, the call then waits for the ssh client to
1063 /// exit, as the ssh time limits of [`connect`](PushSession::connect) state.
1064 ///
1065 /// Over HTTP, the call sends `DELETE`, also on a broken session. A 204 is
1066 /// success, and so is a 404, which the server gives for a session that it
1067 /// ended already.
1068 ///
1069 /// # Errors
1070 ///
1071 /// - [`Error::InvalidInput`] if the session is broken. Over HTTP, the
1072 /// call sends `DELETE` first.
1073 /// - [`Error::Io`] if the write of `Abort` fails.
1074 /// - [`Error::Transport`] over ssh, if the write of `Abort` fails with an
1075 /// I/O error and the ssh client exits with a failure status. The error
1076 /// names the status.
1077 /// - An `Error` message from the server over HTTP, as the [`Error`]
1078 /// variant of its code.
1079 /// - [`Error::Fetch`] over HTTP, for a failure of the HTTP client.
1080 /// - [`Error::Transport`] over HTTP, for a status that the endpoint does
1081 /// not give, or for a body that is not one frame.
1082 /// - [`Error::Io`] over HTTP, for a failed read of the response body.
1083 pub async fn abort(self) -> Result<()> {
1084 let (slot, transport) = match self.inner.link {
1085 Link::Stream { slot, transport } => (slot, transport),
1086 Link::Http(link) => return link.abort().await,
1087 };
1088 let result = match into_stream(slot) {
1089 Ok(mut stream) => {
1090 let result = stream.write_raw(&Message::Abort).await;
1091 let _ = stream.close().await;
1092 result
1093 }
1094 Err(e) => Err(e),
1095 };
1096 finish(transport, result).await
1097 }
1098}
1099
1100/// A session that commits: the parts of a stream session, or the commit of
1101/// an HTTP session. The value lives for one match, so the size of the
1102/// stream variant costs nothing.
1103#[allow(clippy::large_enum_variant)]
1104enum Committing {
1105 Stream {
1106 slot: Mutex<Slot>,
1107 transport: Option<Transport>,
1108 counters: Arc<Counters>,
1109 checked: Result<()>,
1110 request: CommitRequest,
1111 names: Vec<String>,
1112 },
1113 /// The HTTP commit holds the response of its request, so its future is
1114 /// boxed, and the future of a stream commit does not hold it.
1115 Http(BoxFuture<'static, Result<PushOutcome>>),
1116}
1117
1118impl SessionInner {
1119 /// Takes the session apart to send `request`, which `checked` checked.
1120 /// `names` are the refs that the `CommitReply` must hold, in order.
1121 fn into_commit(
1122 self,
1123 checked: Result<()>,
1124 request: CommitRequest,
1125 names: Vec<String>,
1126 ) -> Committing {
1127 let SessionInner {
1128 server,
1129 counters,
1130 link,
1131 ..
1132 } = self;
1133 match link {
1134 Link::Stream { slot, transport } => Committing::Stream {
1135 slot,
1136 transport,
1137 counters,
1138 checked,
1139 request,
1140 names,
1141 },
1142 Link::Http(link) => Committing::Http(Box::pin(async move {
1143 link.commit(&server, &counters, checked, request, &names)
1144 .await
1145 })),
1146 }
1147 }
1148
1149 /// Sends `Commit` with `request`, which `checked` checked, and returns
1150 /// the outcome from the reply. `names` are the refs that the
1151 /// `CommitReply` must hold, in order.
1152 async fn send_commit(
1153 self,
1154 checked: Result<()>,
1155 request: CommitRequest,
1156 names: Vec<String>,
1157 ) -> Result<PushOutcome> {
1158 let (slot, transport, counters, checked, request, names) =
1159 match self.into_commit(checked, request, names) {
1160 Committing::Stream {
1161 slot,
1162 transport,
1163 counters,
1164 checked,
1165 request,
1166 names,
1167 } => (slot, transport, counters, checked, request, names),
1168 Committing::Http(commit) => return commit.await,
1169 };
1170 let stream = into_stream(slot);
1171 let result = match (checked, stream) {
1172 (Ok(()), Ok(stream)) => commit_on(stream, request, &names, &counters).await,
1173 (Ok(()), Err(e)) => Err(e),
1174 (Err(e), stream) => {
1175 // The server reads the end of the stream.
1176 drop(stream);
1177 Err(e)
1178 }
1179 };
1180 finish(transport, result).await
1181 }
1182}
1183
1184/// Returns the refs that the server commit `sc` writes: the branch, then
1185/// each tag.
1186fn server_commit_refs(sc: &ServerCommit) -> impl Iterator<Item = &str> {
1187 std::iter::once(sc.branch.as_str()).chain(sc.tags.iter().map(String::as_str))
1188}
1189
1190/// Runs the checks of a server commit `sc` against the facts of `server`,
1191/// other than the length of the `Commit` frame: the names of the refs, the
1192/// depth of each metadata value, and the length of the longest
1193/// `CommitReply`.
1194fn check_server_commit_fields(server: &ServerInfo, sc: &ServerCommit) -> Result<()> {
1195 let named: HashSet<&str> = server.refs.iter().map(|r| r.name.as_str()).collect();
1196 let mut seen = HashSet::new();
1197 for name in server_commit_refs(sc) {
1198 if !named.contains(name) {
1199 return Err(invalid(format!(
1200 "ref '{name}' was not named when the session opened"
1201 )));
1202 }
1203 if !seen.insert(name) {
1204 return Err(invalid(format!(
1205 "ref '{name}' is named twice in the server commit"
1206 )));
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}