Skip to main content

ostrya_remote/
push_tree.rs

1//! The push of a local directory: the walk and the hash pass, and one session
2//! that sends the objects that the server lacks and asks the server to commit
3//! the tree.
4
5use std::collections::HashSet;
6use std::path::Path;
7
8use futures_io::{AsyncRead, AsyncWrite};
9use ostrya_core::{Checksum, MAX_COLLECTION_ID_LEN, Ref, Type, Value};
10
11use crate::error::{Error, Result};
12use crate::proto::ServerCommit;
13use crate::session::{
14    Compression, PushOutcome, PushProgress, PushSession, ServerInfo, SessionOptions, deflate_level,
15    invalid,
16};
17use crate::transport::{Endpoint, PreparedSession};
18use crate::tree::{EntryFilter, ScanOptions, TreeModel};
19
20/// The metadata keys of the bindings, which the server writes.
21const BINDING_KEYS: [&str; 2] = ["ostree.ref-binding", "ostree.collection-binding"];
22
23/// The options of a tree push.
24///
25/// [`push_tree`], [`push_tree_prepared`], and [`push_tree_over_stream`] take
26/// them. The struct carries no `#[non_exhaustive]`. A caller builds it with
27/// `..Default::default()`. The default branch is the local ref with an
28/// empty name, which the push refuses, so a caller sets
29/// [`onto`](TreePushOptions::onto).
30pub struct TreePushOptions {
31    /// The branch of the server that the server moves to the new commit: a
32    /// local ref `NAME`, or a ref `@ID:NAME` of the collection `ID`.
33    ///
34    /// The parent of the commit is the commit of the branch on the server
35    /// when the server writes the commit. If the branch is absent, the commit
36    /// has no parent.
37    pub onto: Ref,
38    /// The tags that the server creates at the new commit, in order.
39    ///
40    /// A tag is a local ref `NAME` or a ref `@ID:NAME`. The branch and each
41    /// tag are in one namespace of the server. A tag that exists on the
42    /// server refuses the push.
43    pub tags: Vec<Ref>,
44    /// The names that the commit binds and that get no ref, in order.
45    ///
46    /// Each name is a plain ref name. The `ostree.ref-binding` of the commit
47    /// holds the name part of the branch and of each tag, and each of these
48    /// names.
49    pub bind_refs: Vec<String>,
50    /// The switch that makes a commit with no parent.
51    ///
52    /// On a branch that exists, the server allows it only for a client that
53    /// can also delete the branch.
54    pub orphan: bool,
55    /// The collection id that a plain branch and each plain tag take.
56    ///
57    /// With `Some(ID)`, a plain branch or tag `NAME` is the ref `@ID:NAME`. A
58    /// branch or tag `@ID:NAME` stays, and a branch or tag `@Y:NAME`, with
59    /// `Y` other than `ID`, refuses the push before the scan. The collection
60    /// does not change [`bind_refs`](TreePushOptions::bind_refs). The server
61    /// writes the refs of its own collection id as its local refs.
62    pub collection: Option<String>,
63    /// The subject of the commit, empty if not set.
64    pub subject: Option<String>,
65    /// The body of the commit, empty if not set.
66    pub body: Option<String>,
67    /// The entries of the `a{sv}` metadata dict of the commit, in order.
68    ///
69    /// Each value is a variant. The server writes the bindings after the
70    /// entries.
71    pub metadata: Vec<(String, Value)>,
72    /// The timestamp of the commit, in seconds since the Unix epoch, UTC.
73    ///
74    /// If this field is not set, the server takes its clock. The push reads
75    /// no environment variable.
76    pub timestamp: Option<u64>,
77    /// The encoding of the content objects.
78    pub compression: Compression,
79    /// The filter that sees each entry of the walk.
80    pub entry_filter: Option<EntryFilter>,
81    /// The maximum number of regular files that the hash pass reads at one
82    /// time.
83    ///
84    /// [`ScanOptions::hash_jobs`] gives the default and the limits.
85    pub hash_jobs: Option<usize>,
86    /// The progress handle of the scan and of the session.
87    ///
88    /// The scan sets its phases in the handle, and the session counts its
89    /// progress into it.
90    pub progress: Option<PushProgress>,
91}
92
93impl Default for TreePushOptions {
94    fn default() -> TreePushOptions {
95        TreePushOptions {
96            onto: Ref::local(String::new()),
97            tags: Vec::new(),
98            bind_refs: Vec::new(),
99            orphan: false,
100            collection: None,
101            subject: None,
102            body: None,
103            metadata: Vec::new(),
104            timestamp: None,
105            compression: Compression::default(),
106            entry_filter: None,
107            hash_jobs: None,
108            progress: None,
109        }
110    }
111}
112
113/// Pushes the directory `root` to `endpoint` as one server commit.
114///
115/// The server makes the commit over the tree, moves the branch to it, and
116/// creates each tag at it, in one transaction. The push runs in this order:
117///
118/// 1. It checks `opts` and refuses each value that [`push_tree_over_stream`]
119///    refuses. Then it makes the transport ready with
120///    [`PushSession::prepare`]. For ssh, it builds the command line. For
121///    HTTP, it builds the HTTP client.
122/// 2. It walks and hashes the tree with [`TreeModel::scan`], with
123///    `entry_filter` and `hash_jobs`.
124/// 3. It starts the ssh client, or sends the first HTTP request. It opens the
125///    session with the branch and the tags in one `Hello`.
126/// 4. It offers each object of the tree in one round of `Have`. It sends the
127///    objects that the server lacks, and then it sends `Commit` with the
128///    server commit.
129///
130/// A refusal of the options, a walk error, and a hash error start no ssh
131/// client, send no request, and open no session. [`push_tree_over_stream`]
132/// gives the rules of the server commit and of the session.
133///
134/// [`PushStats::elapsed`](crate::session::PushStats::elapsed) of the outcome
135/// covers the session alone, from the open of the session. It excludes the
136/// time of the scan.
137///
138/// Under the tokio backend, the call must run within a runtime that has the
139/// IO driver and the time driver enabled, as [`PushSession::connect`] states.
140///
141/// # Errors
142///
143/// - Each error of [`push_tree_prepared`](push_tree_prepared#errors).
144/// - [`Error::InvalidInput`] if the ssh command or the receive command is
145///   empty or holds only white space, or if the value of `OSTRYA_SSH_COMMAND`
146///   is not UTF-8. The [empty values](crate::SshOptions#empty-values) give
147///   the full rule.
148/// - [`Error::InvalidInput`] if the options of an HTTP endpoint do not name
149///   exactly one mirror, or if
150///   [`check_base_url`](ostrya_fetch::check_base_url) refuses the mirror.
151/// - [`Error::Fetch`] if [`Fetcher::new`](ostrya_fetch::Fetcher::new) refuses
152///   the options of an HTTP endpoint, for example a credential to an
153///   `http://` address without `allow_cleartext_credentials`.
154///
155/// [`Error::InvalidInput`]: crate::Error::InvalidInput
156/// [`Error::Fetch`]: crate::Error::Fetch
157pub async fn push_tree(
158    endpoint: Endpoint,
159    root: &Path,
160    opts: TreePushOptions,
161) -> Result<PushOutcome> {
162    let (scan, push) = Prepared::new(opts)?;
163    let transport = PushSession::prepare(endpoint).await?;
164    push.scan_and_run(transport, root, scan).await
165}
166
167/// Pushes the directory `root` as one server commit over a prepared
168/// transport.
169///
170/// `session` is a transport that [`PushSession::prepare`] made ready. The
171/// push is that of [`push_tree`] with the transport checks done first, so a
172/// caller can do them before the work that builds `opts`. For example, the
173/// caller can read a large body file after the checks.
174///
175/// The push checks `opts` as [`push_tree`] does, then scans the tree, and then
176/// opens `session`. A refusal of the options, a walk error, and a hash error
177/// start no ssh client, send no request, and open no session. The other rules
178/// are those of [`push_tree`].
179///
180/// # Errors
181///
182/// - Each error of [`push_tree_over_stream`](push_tree_over_stream#errors).
183/// - [`Error::Transport`] if the ssh client cannot be started, or if it exits
184///   with a failure status after the session fails with an I/O error.
185/// - [`Error::Transport`] if an HTTP server answers with a status that the
186///   receive endpoint does not give, or with a body that is not one frame.
187/// - [`Error::Unauthorized`] if an HTTP server refuses the credential of the
188///   session with an `Error` message of the code `unauthorized`.
189/// - [`Error::Fetch`] for a failure of the HTTP client.
190///
191/// [`Error::Transport`]: crate::Error::Transport
192/// [`Error::Unauthorized`]: crate::Error::Unauthorized
193/// [`Error::Fetch`]: crate::Error::Fetch
194pub async fn push_tree_prepared(
195    session: PreparedSession,
196    root: &Path,
197    opts: TreePushOptions,
198) -> Result<PushOutcome> {
199    let (scan, push) = Prepared::new(opts)?;
200    push.scan_and_run(session, root, scan).await
201}
202
203/// Pushes the directory `root` as one server commit over a pair of byte
204/// streams.
205///
206/// `input` comes from the server, and `output` goes to it. The push scans
207/// the tree before it writes the first byte to `output`.
208///
209/// # Refusals
210///
211/// Before the scan, the push refuses these values of `opts`:
212///
213/// - a `collection` that fails
214///   [`is_collection_id`](ostrya_core::is_collection_id) or is longer than
215///   255 bytes
216/// - a branch or a tag that is a remote ref, that fails [`Ref::validate`],
217///   for example a name that holds `^`, or that is a local ref of 64
218///   lowercase hex characters, which a revision reads as a commit checksum
219/// - a branch or a tag `@Y:NAME` under a `collection` other than `Y`
220/// - after the collection applies, a tag that is the branch, a tag named
221///   twice, and a branch and tags of two collections, `@X:NAME` and
222///   `@Y:NAME`
223/// - a bound name that holds `:` or that fails the ref-name rule
224/// - a DEFLATE level outside 1 through 9
225/// - an empty key in `metadata`, the key `ostree.ref-binding` or
226///   `ostree.collection-binding`, which the server writes, and a value that
227///   is not a variant
228///
229/// The scan refuses `hash_jobs` of `Some(0)` before the walk starts. If the
230/// push refuses a value, or if the walk or the hash pass fails, the push
231/// writes nothing.
232///
233/// # Server commit
234///
235/// The session opens with the text of the branch and then of each tag, after
236/// [`collection`](TreePushOptions::collection) applied. After `HelloReply`,
237/// the push refuses a tag that the server holds with
238/// [`Error::RefMismatch`]. Then it runs
239/// [`PushSession::check_server_commit`]: the branch and each tag must be in
240/// one namespace after the server maps the refs of its collection id to its
241/// local refs, the `NAME` of a ref `@OWN:NAME` of the collection id `OWN`
242/// of the server must not be 64 lowercase hex characters, a commit must hold
243/// each metadata value, and the `Commit` frame of the server commit and the
244/// longest `CommitReply` must fit in the `max-frame` of the server. Each
245/// refusal comes before the push offers an object.
246///
247/// The push offers each object of the tree in one round of `Have`, and sends
248/// the objects that the server lacks. It sends no commit object and no
249/// detached metadata. Then it sends the server commit with the root dirtree
250/// and the root dirmeta of the tree, the subject, the body, the entries of
251/// `metadata`, the timestamp, the tags, the bound names, and `orphan`.
252///
253/// The server reads the tip of the branch and writes the commit with that tip
254/// as its parent, the bindings of its namespace, and the keys of its own
255/// signing rule. [`PushOutcome::commit`] holds the commit that the server
256/// wrote.
257///
258/// The server verifies each object. If the bytes of a file change after the
259/// hash pass, the server sends an `Error` message and no ref changes.
260///
261/// # Failures
262///
263/// A failure after the session opens and before `Commit` ends the session, and
264/// the push returns that failure. If the stream is still usable, the push
265/// writes `Abort`. Over HTTP, the push ends the session with `DELETE`.
266/// [`PushStats::elapsed`](crate::session::PushStats::elapsed)
267/// covers the session alone.
268///
269/// # Errors
270///
271/// - [`Error::InvalidInput`] for each value of [Refusals](#refusals), and if
272///   `hash_jobs` is `Some(0)`.
273/// - [`Error::Walk`] if the walk or the hash pass fails. [`TreeModel::scan`]
274///   gives the `io::ErrorKind` of each case.
275/// - [`Error::RefMismatch`] if `HelloReply` reports a commit for a tag.
276/// - [`Error::InvalidInput`] if the branch and the tags are in two
277///   namespaces of the server, or if the branch or a tag is `@OWN:NAME` for
278///   the collection id `OWN` of the server and `NAME` is 64 lowercase hex
279///   characters.
280/// - [`Error::InvalidInput`] if a commit cannot hold a value of `metadata`.
281///   In a commit, a value can hold two levels of containers fewer than a
282///   variant.
283/// - [`Error::LimitExceeded`] if the `Commit` frame of the server commit, or
284///   the longest `CommitReply` to it, is over the `max-frame` of the
285///   server.
286/// - [`Error::Source`] if the send pass cannot open or read a file of the
287///   tree. The error of a failed open is the [`Error::Walk`] of that file.
288/// - [`Error::Protocol`] or [`Error::LimitExceeded`] if the codec refuses a
289///   frame of the session.
290/// - [`Error::Io`] for an I/O error of `input` or `output`.
291/// - [`Error::CommitOutcomeUnknown`] if the session ends after `Commit` with
292///   no reply that the client can read.
293/// - An `Error` message from the server, as the [`Error`] variant of its code.
294///   An example is [`Error::RefDenied`] if the client has no `c` on the
295///   branch, or if the hooks of the server take no server commit.
296///
297/// [`Error`]: crate::Error
298/// [`Error::InvalidInput`]: crate::Error::InvalidInput
299/// [`Error::Walk`]: crate::Error::Walk
300/// [`Error::RefMismatch`]: crate::Error::RefMismatch
301/// [`Error::LimitExceeded`]: crate::Error::LimitExceeded
302/// [`Error::Source`]: crate::Error::Source
303/// [`Error::Protocol`]: crate::Error::Protocol
304/// [`Error::Io`]: crate::Error::Io
305/// [`Error::CommitOutcomeUnknown`]: crate::Error::CommitOutcomeUnknown
306/// [`Error::RefDenied`]: crate::Error::RefDenied
307pub async fn push_tree_over_stream<R, W>(
308    input: R,
309    output: W,
310    root: &Path,
311    opts: TreePushOptions,
312) -> Result<PushOutcome>
313where
314    R: AsyncRead + Unpin + Send + 'static,
315    W: AsyncWrite + Unpin + Send + 'static,
316{
317    let (scan, push) = Prepared::new(opts)?;
318    let model = push.scan(root, scan).await?;
319    let session =
320        PushSession::over_stream(input, output, &push.refs, push.session_options()).await?;
321    push.run(session, model).await
322}
323
324/// A tree that [`scan_tree`] walked and hashed, with the checked inputs of
325/// its commit.
326///
327/// A writer that makes the commit itself takes this value in place of a
328/// session. An example is the push of a tree to a bucket repository in the
329/// `ostrya` crate.
330#[non_exhaustive]
331pub struct ScannedTree {
332    /// The model of the tree, which is the source of its objects.
333    pub model: TreeModel,
334    /// The commit that the options describe.
335    ///
336    /// The root dirtree and the root dirmeta are those of
337    /// [`model`](ScannedTree::model). The metadata entries are the bytes of
338    /// each value as a `v` in normal form, in the order of the options. A
339    /// commit can hold each value. The branch and the tags are the text of
340    /// [`branch`](ScannedTree::branch) and [`tags`](ScannedTree::tags).
341    pub commit: ServerCommit,
342    /// The branch, after [`TreePushOptions::collection`] applied.
343    pub branch: Ref,
344    /// The tags, after [`TreePushOptions::collection`] applied.
345    pub tags: Vec<Ref>,
346    /// The encoding of the content objects, from
347    /// [`TreePushOptions::compression`].
348    pub compression: Compression,
349    /// The progress handle, from [`TreePushOptions::progress`].
350    pub progress: Option<PushProgress>,
351}
352
353/// Checks `opts` and scans the directory `root`, with no transport.
354///
355/// The call refuses each value that [`push_tree_over_stream`] refuses before
356/// its scan, as its [Refusals](push_tree_over_stream#refusals) state. It also
357/// refuses a metadata value that a commit cannot hold, which a session push
358/// refuses after the session opens. It does not check the `max-frame` of a
359/// server, which limits the `Commit` frame of a session push. The writer
360/// applies its own size limit to the commit. Then it walks and hashes the
361/// tree with [`TreeModel::scan`], with `entry_filter` and `hash_jobs`, and
362/// sets the phases of the scan in the progress handle. The call sends nothing
363/// and writes nothing.
364///
365/// # Errors
366///
367/// - [`Error::InvalidInput`] for each value of
368///   [Refusals](push_tree_over_stream#refusals), and if `hash_jobs` is
369///   `Some(0)`.
370/// - [`Error::InvalidInput`] if a commit cannot hold a value of `metadata`.
371///   In a commit, a value can hold two levels of containers fewer than a
372///   variant.
373/// - [`Error::Walk`] if the walk or the hash pass fails. [`TreeModel::scan`]
374///   gives the `io::ErrorKind` of each case.
375///
376/// [`Error::InvalidInput`]: crate::Error::InvalidInput
377/// [`Error::Walk`]: crate::Error::Walk
378pub async fn scan_tree(root: &Path, opts: TreePushOptions) -> Result<ScannedTree> {
379    let (scan, push) = Prepared::new(opts)?;
380    crate::proto::check_server_commit_metadata(&push.commit)?;
381    let model = push.scan(root, scan).await?;
382    let Prepared {
383        mut commit,
384        branch,
385        tags,
386        compression,
387        progress,
388        ..
389    } = push;
390    commit.root_dirtree = model.root_dirtree();
391    commit.root_dirmeta = model.root_dirmeta();
392    Ok(ScannedTree {
393        model,
394        commit,
395        branch,
396        tags,
397        compression,
398        progress,
399    })
400}
401
402/// The checked options of a tree push, without the options of the scan.
403struct Prepared {
404    /// The refs of `Hello`: the branch, then each tag.
405    refs: Vec<String>,
406    /// The server commit, with no root checksums before the scan.
407    commit: ServerCommit,
408    /// The branch, after the collection of the push applied.
409    branch: Ref,
410    /// The tags, after the collection of the push applied.
411    tags: Vec<Ref>,
412    compression: Compression,
413    progress: Option<PushProgress>,
414}
415
416impl Prepared {
417    /// Checks `opts`. Returns the options of the scan as a separate value,
418    /// because the entry filter is not `Sync`.
419    fn new(opts: TreePushOptions) -> Result<(ScanOptions, Prepared)> {
420        let TreePushOptions {
421            onto,
422            tags,
423            bind_refs,
424            orphan,
425            collection,
426            subject,
427            body,
428            metadata,
429            timestamp,
430            compression,
431            entry_filter,
432            hash_jobs,
433            progress,
434        } = opts;
435        if let Some(id) = &collection {
436            check_collection(id)?;
437        }
438        let (branch, tags) = check_names(onto, tags, &bind_refs, collection.as_deref())?;
439        deflate_level(compression)?;
440        let metadata = metadata_entries(metadata)?;
441        let scan = ScanOptions {
442            entry_filter,
443            hash_jobs,
444        };
445        let refs: Vec<String> = std::iter::once(&branch)
446            .chain(&tags)
447            .map(Ref::to_string)
448            .collect();
449        // The scan gives the root checksums.
450        let unset = Checksum::from_bytes([0; 32]);
451        let push = Prepared {
452            commit: ServerCommit {
453                branch: refs[0].clone(),
454                tags: refs[1..].to_vec(),
455                bind_refs,
456                root_dirtree: unset,
457                root_dirmeta: unset,
458                subject: subject.unwrap_or_default(),
459                body: body.unwrap_or_default(),
460                metadata,
461                timestamp,
462                orphan,
463            },
464            refs,
465            branch,
466            tags,
467            compression,
468            progress,
469        };
470        Ok((scan, push))
471    }
472
473    /// Walks and hashes the tree at `root`, and sets the phases of the scan
474    /// in the progress handle.
475    async fn scan(&self, root: &Path, scan: ScanOptions) -> Result<TreeModel> {
476        TreeModel::scan_with(root, scan, self.progress.as_ref()).await
477    }
478
479    /// Scans the tree at `root`, opens `transport`, and runs the push.
480    async fn scan_and_run(
481        self,
482        transport: PreparedSession,
483        root: &Path,
484        scan: ScanOptions,
485    ) -> Result<PushOutcome> {
486        let model = self.scan(root, scan).await?;
487        let session = transport.open(&self.refs, self.session_options()).await?;
488        // The future of the run is large. The box keeps it out of the future
489        // of the push.
490        Box::pin(self.run(session, model)).await
491    }
492
493    fn session_options(&self) -> SessionOptions {
494        SessionOptions {
495            progress: self.progress.clone(),
496            ..SessionOptions::default()
497        }
498    }
499
500    /// Runs the push over `session`. A failure before `Commit` ends the
501    /// session, with `Abort` if the stream is still usable.
502    async fn run(self, session: PushSession, model: TreeModel) -> Result<PushOutcome> {
503        let mut commit = self.commit;
504        commit.root_dirtree = model.root_dirtree();
505        commit.root_dirmeta = model.root_dirmeta();
506        match upload(&session, &model, &commit, self.compression).await {
507            Ok(()) => {
508                drop(model);
509                session.server_commit(commit).await
510            }
511            Err(e) => {
512                let _ = session.abort().await;
513                Err(e)
514            }
515        }
516    }
517}
518
519/// Runs the checks after `HelloReply`, the one `Have` round, and the upload
520/// of the objects of `model` that the server lacks.
521async fn upload(
522    session: &PushSession,
523    model: &TreeModel,
524    commit: &ServerCommit,
525    compression: Compression,
526) -> Result<()> {
527    check_tags_absent(session.server(), &commit.tags)?;
528    session.check_server_commit(commit)?;
529    let names = model.object_names();
530    let missing = session.missing(&names).await?;
531    drop(names);
532    session.send(model, &missing, &[], compression).await
533}
534
535/// Refuses a tag that `server` reports at a commit, with
536/// [`Error::RefMismatch`]. The server refuses it at `Commit` too.
537fn check_tags_absent(server: &ServerInfo, tags: &[String]) -> Result<()> {
538    match tags
539        .iter()
540        .find_map(|tag| server.tip(tag).map(|tip| (tag, tip)))
541    {
542        Some((tag, current)) => Err(Error::RefMismatch {
543            message: format!("ref '{tag}' is at {current}"),
544            name: tag.clone(),
545            current: Some(current),
546        }),
547        None => Ok(()),
548    }
549}
550
551/// Refuses a ref that the server commit writes: a remote ref, a ref that
552/// fails [`Ref::validate`] (which includes a name that holds `^`), and a
553/// local ref of 64 lowercase hex characters. `what` names the ref in the
554/// message. [`PushSession::check_server_commit`] refuses a ref `@OWN:NAME`
555/// of that form after `HelloReply`, when the collection id `OWN` of the
556/// server is known.
557fn check_ref(r: &Ref, what: &str) -> Result<()> {
558    if let Ref::Remote { .. } = r {
559        return Err(invalid(format!(
560            "{what} '{r}' is a remote ref; a tree push writes no remote ref"
561        )));
562    }
563    if r.validate().is_err() {
564        return Err(invalid(format!("{what} '{r}' is not a valid ref name")));
565    }
566    if let Ref::Local { name } = r
567        && ostrya_core::is_checksum_shaped(name)
568    {
569        return Err(invalid(format!(
570            "{what} '{r}' is 64 hex characters, which a revision reads as a commit checksum"
571        )));
572    }
573    Ok(())
574}
575
576/// Returns the ref `r` under the collection `collection` of the push: a
577/// local ref `NAME` becomes `@ID:NAME`, a ref `@ID:NAME` stays, and a ref of
578/// another collection is refused. `what` names the ref in the message.
579fn in_collection(r: Ref, collection: Option<&str>, what: &str) -> Result<Ref> {
580    let Some(id) = collection else {
581        return Ok(r);
582    };
583    r.in_collection(id).map_err(|r| {
584        let Ref::Collection { id: other, .. } = &r else {
585            unreachable!("a refused ref is a collection ref");
586        };
587        invalid(format!(
588            "{what} '{r}' names the collection '{other}', and the push names the collection \
589             '{id}'"
590        ))
591    })
592}
593
594/// Checks the branch, the tags, and the bound names, and returns the branch
595/// and the tags after the collection `collection` applied.
596///
597/// The call refuses a bad branch, a bad tag, and a ref of another
598/// collection. After the collection applies, it refuses a tag that is the
599/// branch, a tag named twice, and a branch and tags of two collections. It
600/// also refuses a bound name that holds `:` or fails the ref-name rule.
601fn check_names(
602    onto: Ref,
603    tags: Vec<Ref>,
604    bind_refs: &[String],
605    collection: Option<&str>,
606) -> Result<(Ref, Vec<Ref>)> {
607    check_ref(&onto, "branch")?;
608    for tag in &tags {
609        check_ref(tag, "tag")?;
610    }
611    let onto = in_collection(onto, collection, "branch")?;
612    let tags = tags
613        .into_iter()
614        .map(|tag| in_collection(tag, collection, "tag"))
615        .collect::<Result<Vec<_>>>()?;
616    let mut seen = HashSet::new();
617    for tag in &tags {
618        if *tag == onto {
619            return Err(invalid(format!("the tag '{tag}' is also the branch")));
620        }
621        if !seen.insert(tag) {
622            return Err(invalid(format!("the tag '{tag}' is named twice")));
623        }
624    }
625    // The server maps the refs of its own collection id to its local refs,
626    // so the check of a local ref and a collection ref comes after
627    // `HelloReply`. Two collections are two namespaces on each server.
628    if let Some((other, r)) = Ref::collection_conflict(std::iter::once(&onto).chain(&tags)) {
629        return Err(invalid(format!(
630            "the refs '{other}' and '{r}' of the server commit are in two namespaces"
631        )));
632    }
633    for name in bind_refs {
634        if name.contains(':') || !ostrya_core::is_ref_name(name) {
635            return Err(invalid(format!(
636                "bound name '{name}' is not a valid ref name"
637            )));
638        }
639    }
640    Ok((onto, tags))
641}
642
643/// Refuses a collection id that fails the collection-id rule or is longer
644/// than [`MAX_COLLECTION_ID_LEN`] bytes.
645fn check_collection(id: &str) -> Result<()> {
646    if id.len() > MAX_COLLECTION_ID_LEN {
647        return Err(invalid(format!(
648            "the collection id of {} bytes is longer than {MAX_COLLECTION_ID_LEN} bytes",
649            id.len()
650        )));
651    }
652    if !ostrya_core::is_collection_id(id) {
653        return Err(invalid(format!("invalid collection id '{id}'")));
654    }
655    Ok(())
656}
657
658/// Returns the metadata entries of a server commit: each key with the bytes of
659/// its value as a `v` in normal form, in order.
660///
661/// An empty key, a binding key, and a value that is not a variant are
662/// [`Error::InvalidInput`].
663fn metadata_entries(entries: Vec<(String, Value)>) -> Result<Vec<(String, Vec<u8>)>> {
664    entries
665        .into_iter()
666        .map(|(key, value)| {
667            if key.is_empty() {
668                return Err(invalid("the metadata holds an empty key"));
669            }
670            if BINDING_KEYS.contains(&key.as_str()) {
671                return Err(invalid(format!(
672                    "the metadata holds the key '{key}', which the server writes"
673                )));
674            }
675            let bytes = ostrya_core::to_bytes(&Type::Variant, &value).map_err(|e| {
676                invalid(format!(
677                    "the metadata value under '{key}' is not a variant: {e}"
678                ))
679            })?;
680            Ok((key, bytes))
681        })
682        .collect()
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688
689    fn refused(opts: TreePushOptions) -> String {
690        match Prepared::new(opts) {
691            Err(Error::InvalidInput(m)) => m,
692            Err(e) => panic!("{e:?}"),
693            Ok(_) => panic!("accepted"),
694        }
695    }
696
697    fn onto(branch: &str) -> TreePushOptions {
698        TreePushOptions {
699            onto: Ref::local(branch),
700            timestamp: Some(1),
701            ..Default::default()
702        }
703    }
704
705    fn strings(items: &[&str]) -> Vec<String> {
706        items.iter().map(|s| s.to_string()).collect()
707    }
708
709    /// Reads each text as a ref.
710    fn refs(items: &[&str]) -> Vec<Ref> {
711        items.iter().map(|s| s.parse().unwrap()).collect()
712    }
713
714    const BAD_NAMES: [&str; 16] = [
715        "", "main^", "a^b", "^", "x/y^", "/a", "a/", "a//b", ".", "..", "a/../b", "a\0b", "a b",
716        "a*", "-a", "a/.b",
717    ];
718
719    #[test]
720    fn the_branch_and_the_tags_are_checked_before_the_scan() {
721        let hex = "ab".repeat(32);
722        for (what, make) in [
723            (
724                "branch",
725                (|r: Ref| TreePushOptions {
726                    onto: r,
727                    ..onto("main")
728                }) as fn(Ref) -> TreePushOptions,
729            ),
730            ("tag", |r: Ref| TreePushOptions {
731                tags: vec![r],
732                ..onto("main")
733            }),
734        ] {
735            let m = refused(make(Ref::remote("origin", "main")));
736            assert!(m.contains("is a remote ref"), "{what}: {m}");
737            for bad in BAD_NAMES {
738                let m = refused(make(Ref::local(bad)));
739                assert!(m.contains("not a valid ref name"), "{what} {bad:?}: {m}");
740                assert!(m.starts_with(what), "{what} {bad:?}: {m}");
741            }
742            let m = refused(make(Ref::collection("no-dot", "a")));
743            assert!(m.contains("not a valid ref name"), "{what}: {m}");
744            assert!(
745                refused(make(Ref::local(hex.as_str()))).contains("commit checksum"),
746                "{what}"
747            );
748        }
749        let m = refused(TreePushOptions {
750            tags: refs(&["t", "main"]),
751            ..onto("main")
752        });
753        assert!(m.contains("'main' is also the branch"), "{m}");
754        let m = refused(TreePushOptions {
755            tags: refs(&["t", "u", "t"]),
756            ..onto("main")
757        });
758        assert!(m.contains("'t' is named twice"), "{m}");
759        let upper = hex.to_uppercase();
760        let (_, push) = Prepared::new(TreePushOptions {
761            tags: refs(&["a/b", "x.y", &upper, &hex[1..], "@org.example.X:t"]),
762            ..onto("main")
763        })
764        .unwrap();
765        assert_eq!(
766            push.refs,
767            ["main", "a/b", "x.y", &upper, &hex[1..], "@org.example.X:t"]
768        );
769        // A collection ref of 64 lowercase hex characters passes here. The
770        // check of the ref after the server maps it to its collection id
771        // comes after `HelloReply`.
772        Prepared::new(TreePushOptions {
773            onto: Ref::collection("org.example.X", hex.as_str()),
774            ..onto("main")
775        })
776        .unwrap();
777    }
778
779    /// The collection applies to a plain branch and to each plain tag. A
780    /// ref of the collection stays, and a ref of another collection is
781    /// refused. Two refs of one text after that are refused, and so are
782    /// refs of two collections.
783    #[test]
784    fn the_collection_names_the_namespace_of_each_plain_ref() {
785        let x = || Some("org.example.X".to_owned());
786        let (_, push) = Prepared::new(TreePushOptions {
787            tags: refs(&["t", "@org.example.X:u"]),
788            bind_refs: strings(&["b"]),
789            collection: x(),
790            ..onto("a")
791        })
792        .unwrap();
793        assert_eq!(
794            push.refs,
795            ["@org.example.X:a", "@org.example.X:t", "@org.example.X:u"]
796        );
797        assert_eq!(push.commit.branch, "@org.example.X:a");
798        assert_eq!(push.commit.tags, ["@org.example.X:t", "@org.example.X:u"]);
799        assert_eq!(push.commit.bind_refs, ["b"]);
800        assert_eq!(push.branch, Ref::collection("org.example.X", "a"));
801        let (_, plain) = Prepared::new(TreePushOptions {
802            onto: Ref::collection("org.example.X", "a"),
803            ..onto("a")
804        })
805        .unwrap();
806        assert_eq!(plain.refs, push.refs[..1]);
807        let m = refused(TreePushOptions {
808            onto: Ref::collection("org.example.Y", "a"),
809            collection: x(),
810            ..onto("a")
811        });
812        assert!(
813            m.contains(
814                "names the collection 'org.example.Y', and the push names the collection \
815                        'org.example.X'"
816            ),
817            "{m}"
818        );
819        let m = refused(TreePushOptions {
820            tags: refs(&["@org.example.Y:t"]),
821            collection: x(),
822            ..onto("a")
823        });
824        assert!(m.starts_with("tag '@org.example.Y:t'"), "{m}");
825        let m = refused(TreePushOptions {
826            tags: refs(&["@org.example.X:a"]),
827            collection: x(),
828            ..onto("a")
829        });
830        assert!(m.contains("'@org.example.X:a' is also the branch"), "{m}");
831        let m = refused(TreePushOptions {
832            onto: Ref::collection("org.example.X", "a"),
833            tags: refs(&["t", "@org.example.Y:u"]),
834            ..onto("a")
835        });
836        assert!(
837            m.contains("'@org.example.X:a' and '@org.example.Y:u'"),
838            "{m}"
839        );
840        // A local ref and a collection ref are one namespace on a server
841        // whose collection id is the id, so the scan does not refuse them.
842        Prepared::new(TreePushOptions {
843            tags: refs(&["@org.example.X:t"]),
844            ..onto("main")
845        })
846        .unwrap();
847    }
848
849    #[test]
850    fn a_bound_name_passes_the_ref_name_rule_with_no_colon() {
851        for bad in BAD_NAMES.iter().copied().chain(["o:main"]) {
852            let m = refused(TreePushOptions {
853                bind_refs: strings(&[bad]),
854                ..onto("main")
855            });
856            assert!(m.contains("bound name"), "{bad:?}: {m}");
857        }
858        // A bound name can repeat, can be the branch, and can be 64 hex
859        // characters, because it gets no ref.
860        let hex = "ab".repeat(32);
861        let (_, push) = Prepared::new(TreePushOptions {
862            bind_refs: strings(&["x", "x", "main", &hex]),
863            ..onto("main")
864        })
865        .unwrap();
866        assert_eq!(push.commit.bind_refs, ["x", "x", "main", hex.as_str()]);
867        assert_eq!(push.refs, ["main"]);
868        // A bound name is plain: the collection does not change it.
869        let (_, push) = Prepared::new(TreePushOptions {
870            bind_refs: strings(&["x"]),
871            collection: Some("org.example.X".into()),
872            ..onto("main")
873        })
874        .unwrap();
875        assert_eq!(push.commit.bind_refs, ["x"]);
876    }
877
878    #[test]
879    fn the_collection_is_checked_before_the_scan() {
880        let longest = format!("org.{}", "a".repeat(251));
881        let over = format!("org.{}", "a".repeat(252));
882        for (id, needle) in [("no-dot", "invalid collection id"), (&*over, "256 bytes")] {
883            let m = refused(TreePushOptions {
884                collection: Some(id.into()),
885                ..onto("main")
886            });
887            assert!(m.contains(needle), "{m}");
888        }
889        let (_, push) = Prepared::new(TreePushOptions {
890            collection: Some(longest.clone()),
891            ..onto("main")
892        })
893        .unwrap();
894        assert_eq!(push.branch, Ref::collection(longest, "main"));
895    }
896
897    #[test]
898    fn the_other_options_are_checked_before_the_scan() {
899        for level in [0, 10] {
900            let m = refused(TreePushOptions {
901                compression: Compression::Deflate { level },
902                ..onto("main")
903            });
904            assert!(m.contains("compression level"), "{m}");
905        }
906        let variant = Value::variant(ostrya_core::Type::Str, Value::Str("v".into()));
907        let m = refused(TreePushOptions {
908            metadata: vec![(String::new(), variant.clone())],
909            ..onto("main")
910        });
911        assert!(m.contains("metadata holds an empty key"), "{m}");
912        for key in BINDING_KEYS {
913            let m = refused(TreePushOptions {
914                metadata: vec![("k".into(), variant.clone()), (key.into(), variant.clone())],
915                ..onto("main")
916            });
917            assert!(
918                m.contains(&format!("'{key}', which the server writes")),
919                "{m}"
920            );
921        }
922        let m = refused(TreePushOptions {
923            metadata: vec![("k".into(), Value::Str("bare".into()))],
924            ..onto("main")
925        });
926        assert!(m.contains("not a variant"), "{m}");
927    }
928
929    #[test]
930    fn the_server_commit_carries_the_options() {
931        let string = |s: &str| Value::variant(ostrya_core::Type::Str, Value::Str(s.into()));
932        let (_, push) = Prepared::new(TreePushOptions {
933            tags: refs(&["t"]),
934            bind_refs: strings(&["b"]),
935            orphan: true,
936            subject: Some("s".into()),
937            body: Some("m".into()),
938            metadata: vec![("z".into(), string("1")), ("a".into(), string("2"))],
939            timestamp: Some(42),
940            ..onto("main")
941        })
942        .unwrap();
943        let sc = push.commit;
944        assert_eq!(sc.branch, "main");
945        assert_eq!(sc.tags, ["t"]);
946        assert_eq!(sc.bind_refs, ["b"]);
947        assert!(sc.orphan);
948        assert_eq!((sc.subject.as_str(), sc.body.as_str()), ("s", "m"));
949        let v = |value: &Value| ostrya_core::to_bytes(&Type::Variant, value).unwrap();
950        assert_eq!(
951            sc.metadata,
952            [
953                ("z".to_owned(), v(&string("1"))),
954                ("a".to_owned(), v(&string("2")))
955            ]
956        );
957        assert_eq!(sc.timestamp, Some(42));
958        let (_, push) = Prepared::new(TreePushOptions {
959            timestamp: None,
960            ..onto("main")
961        })
962        .unwrap();
963        assert_eq!(push.commit.timestamp, None);
964        assert_eq!(push.commit.subject, "");
965    }
966
967    #[test]
968    fn a_tag_that_the_server_holds_is_ref_mismatch() {
969        use crate::proto::{Encoding, RefState};
970        let tip = Checksum::from_bytes([5; 32]);
971        let server = ServerInfo {
972            version: 1,
973            mode: "archive".into(),
974            collection_id: None,
975            max_frame: 1 << 20,
976            max_have: 16_384,
977            encodings: vec![Encoding::Raw],
978            parallel_uploads: 1,
979            refs: [("main", Some(tip)), ("a", None), ("b", Some(tip))]
980                .into_iter()
981                .map(|(name, commit)| RefState {
982                    name: name.into(),
983                    commit,
984                })
985                .collect(),
986        };
987        check_tags_absent(&server, &strings(&["a"])).unwrap();
988        match check_tags_absent(&server, &strings(&["a", "b"])) {
989            Err(Error::RefMismatch { name, current, .. }) => {
990                assert_eq!(name, "b");
991                assert_eq!(current, Some(tip));
992            }
993            other => panic!("{other:?}"),
994        }
995    }
996
997    /// `scan_tree` refuses a metadata value that a commit cannot hold before
998    /// the walk, and gives the commit the root checksums of the model.
999    #[test]
1000    fn scan_tree_checks_the_depth_and_fills_the_roots() {
1001        let root =
1002            std::env::temp_dir().join(format!("ostrya-remote-scan-tree-{}", std::process::id()));
1003        let _ = std::fs::remove_dir_all(&root);
1004        std::fs::create_dir_all(root.join("dir")).unwrap();
1005        std::fs::write(root.join("dir/file"), b"file").unwrap();
1006        let deep = (0..126).fold(Value::Byte(1), |value, _| {
1007            Value::Maybe(Some(Box::new(value)))
1008        });
1009        let ty = (0..126).fold(Type::Byte, |ty, _| Type::maybe(ty));
1010        let absent = root.join("absent");
1011        // The walk root is absent, so a refusal shows that the check runs
1012        // before the walk.
1013        match ostrya_rt::block_on(scan_tree(
1014            &absent,
1015            TreePushOptions {
1016                metadata: vec![("deep".into(), Value::variant(ty, deep))],
1017                ..onto("main")
1018            },
1019        )) {
1020            Err(Error::InvalidInput(m)) => assert!(m.contains("cannot hold"), "{m}"),
1021            other => panic!("{:?}", other.map(|_| ())),
1022        }
1023        let scanned = ostrya_rt::block_on(scan_tree(
1024            &root,
1025            TreePushOptions {
1026                collection: Some("org.example.A".into()),
1027                compression: Compression::Deflate { level: 3 },
1028                ..onto("main")
1029            },
1030        ));
1031        let _ = std::fs::remove_dir_all(&root);
1032        let scanned = scanned.unwrap();
1033        assert_eq!(scanned.commit.root_dirtree, scanned.model.root_dirtree());
1034        assert_eq!(scanned.commit.root_dirmeta, scanned.model.root_dirmeta());
1035        assert_eq!(scanned.commit.branch, "@org.example.A:main");
1036        assert_eq!(scanned.commit.timestamp, Some(1));
1037        assert_eq!(scanned.branch, Ref::collection("org.example.A", "main"));
1038        assert!(scanned.tags.is_empty());
1039        assert_eq!(scanned.compression, Compression::Deflate { level: 3 });
1040        // Two dirtrees, one dirmeta that the two directories share, and the
1041        // file.
1042        assert_eq!(scanned.model.object_names().len(), 4);
1043    }
1044
1045    /// On a reused handle, the filter sees `Scanning` for each entry. The
1046    /// hook gets one call with `Scanning` before the walk, and one call with
1047    /// `Hashing` after it.
1048    #[test]
1049    fn the_scan_shows_scanning_during_the_walk_and_hashing_after_it() {
1050        use std::sync::{Arc, Mutex};
1051
1052        use crate::PushPhase;
1053        use crate::tree::EntryAction;
1054
1055        /// One call to the hook or to the entry filter, in the order of the
1056        /// calls.
1057        #[derive(Debug, PartialEq, Eq)]
1058        enum Call {
1059            Hook(PushPhase),
1060            Filter,
1061        }
1062
1063        let root =
1064            std::env::temp_dir().join(format!("ostrya-remote-scan-phases-{}", std::process::id()));
1065        let _ = std::fs::remove_dir_all(&root);
1066        std::fs::create_dir_all(root.join("dir")).unwrap();
1067        std::fs::write(root.join("dir/file"), b"file").unwrap();
1068        let calls: Arc<Mutex<Vec<Call>>> = Arc::default();
1069        let hook_calls = Arc::clone(&calls);
1070        // A reused handle holds the phase of an earlier push.
1071        let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
1072            hook_calls.lock().unwrap().push(Call::Hook(snapshot.phase));
1073        }));
1074        progress.set_phase(PushPhase::Committing);
1075        calls.lock().unwrap().clear();
1076        let seen = Arc::new(Mutex::new(Vec::new()));
1077        let record = (seen.clone(), progress.clone(), Arc::clone(&calls));
1078        let filter: EntryFilter = Box::new(move |_path, _meta| {
1079            record.0.lock().unwrap().push(record.1.snapshot().phase);
1080            record.2.lock().unwrap().push(Call::Filter);
1081            EntryAction::Keep
1082        });
1083        let scan = ScanOptions {
1084            entry_filter: Some(filter),
1085            hash_jobs: None,
1086        };
1087        let model = ostrya_rt::block_on(TreeModel::scan_with(&root, scan, Some(&progress)));
1088        let _ = std::fs::remove_dir_all(&root);
1089        model.unwrap();
1090        let seen = seen.lock().unwrap();
1091        assert_eq!(seen.len(), 3, "{seen:?}");
1092        assert!(seen.iter().all(|p| *p == PushPhase::Scanning), "{seen:?}");
1093        assert_eq!(progress.snapshot().phase, PushPhase::Hashing);
1094        assert_eq!(
1095            *calls.lock().unwrap(),
1096            [
1097                Call::Hook(PushPhase::Scanning),
1098                Call::Filter,
1099                Call::Filter,
1100                Call::Filter,
1101                Call::Hook(PushPhase::Hashing),
1102            ]
1103        );
1104    }
1105
1106    /// The hook of a new handle gets one call with `Scanning` before the
1107    /// filter sees the first entry, and one call with `Hashing` after the
1108    /// filter sees the last entry.
1109    #[test]
1110    fn a_new_handle_gets_a_scanning_call_before_the_walk_and_a_hashing_call_after_it() {
1111        use std::sync::{Arc, Mutex};
1112
1113        use crate::PushPhase;
1114        use crate::tree::EntryAction;
1115
1116        /// One call to the hook or to the entry filter, in the order of the
1117        /// calls.
1118        #[derive(Debug, PartialEq, Eq)]
1119        enum Call {
1120            Hook(PushPhase),
1121            Filter,
1122        }
1123
1124        let root =
1125            std::env::temp_dir().join(format!("ostrya-remote-scan-hook-{}", std::process::id()));
1126        let _ = std::fs::remove_dir_all(&root);
1127        std::fs::create_dir_all(root.join("dir")).unwrap();
1128        std::fs::write(root.join("dir/file"), b"file").unwrap();
1129        let calls: Arc<Mutex<Vec<Call>>> = Arc::default();
1130        let hook_calls = Arc::clone(&calls);
1131        // A new handle holds the phase `Scanning`.
1132        let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
1133            hook_calls.lock().unwrap().push(Call::Hook(snapshot.phase));
1134        }));
1135        let filter_calls = Arc::clone(&calls);
1136        let filter: EntryFilter = Box::new(move |_path, _meta| {
1137            filter_calls.lock().unwrap().push(Call::Filter);
1138            EntryAction::Keep
1139        });
1140        let scan = ScanOptions {
1141            entry_filter: Some(filter),
1142            hash_jobs: None,
1143        };
1144        let model = ostrya_rt::block_on(TreeModel::scan_with(&root, scan, Some(&progress)));
1145        let _ = std::fs::remove_dir_all(&root);
1146        model.unwrap();
1147        // The filter sees the root, `dir`, and `dir/file`.
1148        assert_eq!(
1149            *calls.lock().unwrap(),
1150            [
1151                Call::Hook(PushPhase::Scanning),
1152                Call::Filter,
1153                Call::Filter,
1154                Call::Filter,
1155                Call::Hook(PushPhase::Hashing),
1156            ]
1157        );
1158    }
1159}