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 related: Vec::new(),
462 timestamp,
463 orphan,
464 },
465 refs,
466 branch,
467 tags,
468 compression,
469 progress,
470 };
471 Ok((scan, push))
472 }
473
474 /// Walks and hashes the tree at `root`, and sets the phases of the scan
475 /// in the progress handle.
476 async fn scan(&self, root: &Path, scan: ScanOptions) -> Result<TreeModel> {
477 TreeModel::scan_with(root, scan, self.progress.as_ref()).await
478 }
479
480 /// Scans the tree at `root`, opens `transport`, and runs the push.
481 async fn scan_and_run(
482 self,
483 transport: PreparedSession,
484 root: &Path,
485 scan: ScanOptions,
486 ) -> Result<PushOutcome> {
487 let model = self.scan(root, scan).await?;
488 let session = transport.open(&self.refs, self.session_options()).await?;
489 // The future of the run is large. The box keeps it out of the future
490 // of the push.
491 Box::pin(self.run(session, model)).await
492 }
493
494 fn session_options(&self) -> SessionOptions {
495 SessionOptions {
496 progress: self.progress.clone(),
497 ..SessionOptions::default()
498 }
499 }
500
501 /// Runs the push over `session`. A failure before `Commit` ends the
502 /// session, with `Abort` if the stream is still usable.
503 async fn run(self, session: PushSession, model: TreeModel) -> Result<PushOutcome> {
504 let mut commit = self.commit;
505 commit.root_dirtree = model.root_dirtree();
506 commit.root_dirmeta = model.root_dirmeta();
507 match upload(&session, &model, &commit, self.compression).await {
508 Ok(()) => {
509 drop(model);
510 session.server_commit(commit).await
511 }
512 Err(e) => {
513 let _ = session.abort().await;
514 Err(e)
515 }
516 }
517 }
518}
519
520/// Runs the checks after `HelloReply`, the one `Have` round, and the upload
521/// of the objects of `model` that the server lacks.
522async fn upload(
523 session: &PushSession,
524 model: &TreeModel,
525 commit: &ServerCommit,
526 compression: Compression,
527) -> Result<()> {
528 check_tags_absent(session.server(), &commit.tags)?;
529 session.check_server_commit(commit)?;
530 let names = model.object_names();
531 let missing = session.missing(&names).await?;
532 drop(names);
533 session.send(model, &missing, &[], compression).await
534}
535
536/// Refuses a tag that `server` reports at a commit, with
537/// [`Error::RefMismatch`]. The server refuses it at `Commit` too.
538fn check_tags_absent(server: &ServerInfo, tags: &[String]) -> Result<()> {
539 match tags
540 .iter()
541 .find_map(|tag| server.tip(tag).map(|tip| (tag, tip)))
542 {
543 Some((tag, current)) => Err(Error::RefMismatch {
544 message: format!("ref '{tag}' is at {current}"),
545 name: tag.clone(),
546 current: Some(current),
547 }),
548 None => Ok(()),
549 }
550}
551
552/// Refuses a ref that the server commit writes: a remote ref, a ref that
553/// fails [`Ref::validate`] (which includes a name that holds `^`), and a
554/// local ref of 64 lowercase hex characters. `what` names the ref in the
555/// message. [`PushSession::check_server_commit`] refuses a ref `@OWN:NAME`
556/// of that form after `HelloReply`, when the collection id `OWN` of the
557/// server is known.
558fn check_ref(r: &Ref, what: &str) -> Result<()> {
559 if let Ref::Remote { .. } = r {
560 return Err(invalid(format!(
561 "{what} '{r}' is a remote ref; a tree push writes no remote ref"
562 )));
563 }
564 if r.validate().is_err() {
565 return Err(invalid(format!("{what} '{r}' is not a valid ref name")));
566 }
567 if let Ref::Local { name } = r
568 && ostrya_core::is_checksum_shaped(name)
569 {
570 return Err(invalid(format!(
571 "{what} '{r}' is 64 hex characters, which a revision reads as a commit checksum"
572 )));
573 }
574 Ok(())
575}
576
577/// Returns the ref `r` under the collection `collection` of the push: a
578/// local ref `NAME` becomes `@ID:NAME`, a ref `@ID:NAME` stays, and a ref of
579/// another collection is refused. `what` names the ref in the message.
580fn in_collection(r: Ref, collection: Option<&str>, what: &str) -> Result<Ref> {
581 let Some(id) = collection else {
582 return Ok(r);
583 };
584 r.in_collection(id).map_err(|r| {
585 let Ref::Collection { id: other, .. } = &r else {
586 unreachable!("a refused ref is a collection ref");
587 };
588 invalid(format!(
589 "{what} '{r}' names the collection '{other}', and the push names the collection \
590 '{id}'"
591 ))
592 })
593}
594
595/// Checks the branch, the tags, and the bound names, and returns the branch
596/// and the tags after the collection `collection` applied.
597///
598/// The call refuses a bad branch, a bad tag, and a ref of another
599/// collection. After the collection applies, it refuses a tag that is the
600/// branch, a tag named twice, and a branch and tags of two collections. It
601/// also refuses a bound name that holds `:` or fails the ref-name rule.
602fn check_names(
603 onto: Ref,
604 tags: Vec<Ref>,
605 bind_refs: &[String],
606 collection: Option<&str>,
607) -> Result<(Ref, Vec<Ref>)> {
608 check_ref(&onto, "branch")?;
609 for tag in &tags {
610 check_ref(tag, "tag")?;
611 }
612 let onto = in_collection(onto, collection, "branch")?;
613 let tags = tags
614 .into_iter()
615 .map(|tag| in_collection(tag, collection, "tag"))
616 .collect::<Result<Vec<_>>>()?;
617 let mut seen = HashSet::new();
618 for tag in &tags {
619 if *tag == onto {
620 return Err(invalid(format!("the tag '{tag}' is also the branch")));
621 }
622 if !seen.insert(tag) {
623 return Err(invalid(format!("the tag '{tag}' is named twice")));
624 }
625 }
626 // The server maps the refs of its own collection id to its local refs,
627 // so the check of a local ref and a collection ref comes after
628 // `HelloReply`. Two collections are two namespaces on each server.
629 if let Some((other, r)) = Ref::collection_conflict(std::iter::once(&onto).chain(&tags)) {
630 return Err(invalid(format!(
631 "the refs '{other}' and '{r}' of the server commit are in two namespaces"
632 )));
633 }
634 for name in bind_refs {
635 if name.contains(':') || !ostrya_core::is_ref_name(name) {
636 return Err(invalid(format!(
637 "bound name '{name}' is not a valid ref name"
638 )));
639 }
640 }
641 Ok((onto, tags))
642}
643
644/// Refuses a collection id that fails the collection-id rule or is longer
645/// than [`MAX_COLLECTION_ID_LEN`] bytes.
646fn check_collection(id: &str) -> Result<()> {
647 if id.len() > MAX_COLLECTION_ID_LEN {
648 return Err(invalid(format!(
649 "the collection id of {} bytes is longer than {MAX_COLLECTION_ID_LEN} bytes",
650 id.len()
651 )));
652 }
653 if !ostrya_core::is_collection_id(id) {
654 return Err(invalid(format!("invalid collection id '{id}'")));
655 }
656 Ok(())
657}
658
659/// Returns the metadata entries of a server commit: each key with the bytes of
660/// its value as a `v` in normal form, in order.
661///
662/// An empty key, a binding key, and a value that is not a variant are
663/// [`Error::InvalidInput`].
664fn metadata_entries(entries: Vec<(String, Value)>) -> Result<Vec<(String, Vec<u8>)>> {
665 entries
666 .into_iter()
667 .map(|(key, value)| {
668 if key.is_empty() {
669 return Err(invalid("the metadata holds an empty key"));
670 }
671 if BINDING_KEYS.contains(&key.as_str()) {
672 return Err(invalid(format!(
673 "the metadata holds the key '{key}', which the server writes"
674 )));
675 }
676 let bytes = ostrya_core::to_bytes(&Type::Variant, &value).map_err(|e| {
677 invalid(format!(
678 "the metadata value under '{key}' is not a variant: {e}"
679 ))
680 })?;
681 Ok((key, bytes))
682 })
683 .collect()
684}
685
686#[cfg(test)]
687mod tests {
688 use super::*;
689
690 fn refused(opts: TreePushOptions) -> String {
691 match Prepared::new(opts) {
692 Err(Error::InvalidInput(m)) => m,
693 Err(e) => panic!("{e:?}"),
694 Ok(_) => panic!("accepted"),
695 }
696 }
697
698 fn onto(branch: &str) -> TreePushOptions {
699 TreePushOptions {
700 onto: Ref::local(branch),
701 timestamp: Some(1),
702 ..Default::default()
703 }
704 }
705
706 fn strings(items: &[&str]) -> Vec<String> {
707 items.iter().map(|s| s.to_string()).collect()
708 }
709
710 /// Reads each text as a ref.
711 fn refs(items: &[&str]) -> Vec<Ref> {
712 items.iter().map(|s| s.parse().unwrap()).collect()
713 }
714
715 const BAD_NAMES: [&str; 16] = [
716 "", "main^", "a^b", "^", "x/y^", "/a", "a/", "a//b", ".", "..", "a/../b", "a\0b", "a b",
717 "a*", "-a", "a/.b",
718 ];
719
720 #[test]
721 fn the_branch_and_the_tags_are_checked_before_the_scan() {
722 let hex = "ab".repeat(32);
723 for (what, make) in [
724 (
725 "branch",
726 (|r: Ref| TreePushOptions {
727 onto: r,
728 ..onto("main")
729 }) as fn(Ref) -> TreePushOptions,
730 ),
731 ("tag", |r: Ref| TreePushOptions {
732 tags: vec![r],
733 ..onto("main")
734 }),
735 ] {
736 let m = refused(make(Ref::remote("origin", "main")));
737 assert!(m.contains("is a remote ref"), "{what}: {m}");
738 for bad in BAD_NAMES {
739 let m = refused(make(Ref::local(bad)));
740 assert!(m.contains("not a valid ref name"), "{what} {bad:?}: {m}");
741 assert!(m.starts_with(what), "{what} {bad:?}: {m}");
742 }
743 let m = refused(make(Ref::collection("no-dot", "a")));
744 assert!(m.contains("not a valid ref name"), "{what}: {m}");
745 assert!(
746 refused(make(Ref::local(hex.as_str()))).contains("commit checksum"),
747 "{what}"
748 );
749 }
750 let m = refused(TreePushOptions {
751 tags: refs(&["t", "main"]),
752 ..onto("main")
753 });
754 assert!(m.contains("'main' is also the branch"), "{m}");
755 let m = refused(TreePushOptions {
756 tags: refs(&["t", "u", "t"]),
757 ..onto("main")
758 });
759 assert!(m.contains("'t' is named twice"), "{m}");
760 let upper = hex.to_uppercase();
761 let (_, push) = Prepared::new(TreePushOptions {
762 tags: refs(&["a/b", "x.y", &upper, &hex[1..], "@org.example.X:t"]),
763 ..onto("main")
764 })
765 .unwrap();
766 assert_eq!(
767 push.refs,
768 ["main", "a/b", "x.y", &upper, &hex[1..], "@org.example.X:t"]
769 );
770 // A collection ref of 64 lowercase hex characters passes here. The
771 // check of the ref after the server maps it to its collection id
772 // comes after `HelloReply`.
773 Prepared::new(TreePushOptions {
774 onto: Ref::collection("org.example.X", hex.as_str()),
775 ..onto("main")
776 })
777 .unwrap();
778 }
779
780 /// The collection applies to a plain branch and to each plain tag. A
781 /// ref of the collection stays, and a ref of another collection is
782 /// refused. Two refs of one text after that are refused, and so are
783 /// refs of two collections.
784 #[test]
785 fn the_collection_names_the_namespace_of_each_plain_ref() {
786 let x = || Some("org.example.X".to_owned());
787 let (_, push) = Prepared::new(TreePushOptions {
788 tags: refs(&["t", "@org.example.X:u"]),
789 bind_refs: strings(&["b"]),
790 collection: x(),
791 ..onto("a")
792 })
793 .unwrap();
794 assert_eq!(
795 push.refs,
796 ["@org.example.X:a", "@org.example.X:t", "@org.example.X:u"]
797 );
798 assert_eq!(push.commit.branch, "@org.example.X:a");
799 assert_eq!(push.commit.tags, ["@org.example.X:t", "@org.example.X:u"]);
800 assert_eq!(push.commit.bind_refs, ["b"]);
801 assert_eq!(push.branch, Ref::collection("org.example.X", "a"));
802 let (_, plain) = Prepared::new(TreePushOptions {
803 onto: Ref::collection("org.example.X", "a"),
804 ..onto("a")
805 })
806 .unwrap();
807 assert_eq!(plain.refs, push.refs[..1]);
808 let m = refused(TreePushOptions {
809 onto: Ref::collection("org.example.Y", "a"),
810 collection: x(),
811 ..onto("a")
812 });
813 assert!(
814 m.contains(
815 "names the collection 'org.example.Y', and the push names the collection \
816 'org.example.X'"
817 ),
818 "{m}"
819 );
820 let m = refused(TreePushOptions {
821 tags: refs(&["@org.example.Y:t"]),
822 collection: x(),
823 ..onto("a")
824 });
825 assert!(m.starts_with("tag '@org.example.Y:t'"), "{m}");
826 let m = refused(TreePushOptions {
827 tags: refs(&["@org.example.X:a"]),
828 collection: x(),
829 ..onto("a")
830 });
831 assert!(m.contains("'@org.example.X:a' is also the branch"), "{m}");
832 let m = refused(TreePushOptions {
833 onto: Ref::collection("org.example.X", "a"),
834 tags: refs(&["t", "@org.example.Y:u"]),
835 ..onto("a")
836 });
837 assert!(
838 m.contains("'@org.example.X:a' and '@org.example.Y:u'"),
839 "{m}"
840 );
841 // A local ref and a collection ref are one namespace on a server
842 // whose collection id is the id, so the scan does not refuse them.
843 Prepared::new(TreePushOptions {
844 tags: refs(&["@org.example.X:t"]),
845 ..onto("main")
846 })
847 .unwrap();
848 }
849
850 #[test]
851 fn a_bound_name_passes_the_ref_name_rule_with_no_colon() {
852 for bad in BAD_NAMES.iter().copied().chain(["o:main"]) {
853 let m = refused(TreePushOptions {
854 bind_refs: strings(&[bad]),
855 ..onto("main")
856 });
857 assert!(m.contains("bound name"), "{bad:?}: {m}");
858 }
859 // A bound name can repeat, can be the branch, and can be 64 hex
860 // characters, because it gets no ref.
861 let hex = "ab".repeat(32);
862 let (_, push) = Prepared::new(TreePushOptions {
863 bind_refs: strings(&["x", "x", "main", &hex]),
864 ..onto("main")
865 })
866 .unwrap();
867 assert_eq!(push.commit.bind_refs, ["x", "x", "main", hex.as_str()]);
868 assert_eq!(push.refs, ["main"]);
869 // A bound name is plain: the collection does not change it.
870 let (_, push) = Prepared::new(TreePushOptions {
871 bind_refs: strings(&["x"]),
872 collection: Some("org.example.X".into()),
873 ..onto("main")
874 })
875 .unwrap();
876 assert_eq!(push.commit.bind_refs, ["x"]);
877 }
878
879 #[test]
880 fn the_collection_is_checked_before_the_scan() {
881 let longest = format!("org.{}", "a".repeat(251));
882 let over = format!("org.{}", "a".repeat(252));
883 for (id, needle) in [("no-dot", "invalid collection id"), (&*over, "256 bytes")] {
884 let m = refused(TreePushOptions {
885 collection: Some(id.into()),
886 ..onto("main")
887 });
888 assert!(m.contains(needle), "{m}");
889 }
890 let (_, push) = Prepared::new(TreePushOptions {
891 collection: Some(longest.clone()),
892 ..onto("main")
893 })
894 .unwrap();
895 assert_eq!(push.branch, Ref::collection(longest, "main"));
896 }
897
898 #[test]
899 fn the_other_options_are_checked_before_the_scan() {
900 for level in [0, 10] {
901 let m = refused(TreePushOptions {
902 compression: Compression::Deflate { level },
903 ..onto("main")
904 });
905 assert!(m.contains("compression level"), "{m}");
906 }
907 let variant = Value::variant(ostrya_core::Type::Str, Value::Str("v".into()));
908 let m = refused(TreePushOptions {
909 metadata: vec![(String::new(), variant.clone())],
910 ..onto("main")
911 });
912 assert!(m.contains("metadata holds an empty key"), "{m}");
913 for key in BINDING_KEYS {
914 let m = refused(TreePushOptions {
915 metadata: vec![("k".into(), variant.clone()), (key.into(), variant.clone())],
916 ..onto("main")
917 });
918 assert!(
919 m.contains(&format!("'{key}', which the server writes")),
920 "{m}"
921 );
922 }
923 let m = refused(TreePushOptions {
924 metadata: vec![("k".into(), Value::Str("bare".into()))],
925 ..onto("main")
926 });
927 assert!(m.contains("not a variant"), "{m}");
928 }
929
930 #[test]
931 fn the_server_commit_carries_the_options() {
932 let string = |s: &str| Value::variant(ostrya_core::Type::Str, Value::Str(s.into()));
933 let (_, push) = Prepared::new(TreePushOptions {
934 tags: refs(&["t"]),
935 bind_refs: strings(&["b"]),
936 orphan: true,
937 subject: Some("s".into()),
938 body: Some("m".into()),
939 metadata: vec![("z".into(), string("1")), ("a".into(), string("2"))],
940 timestamp: Some(42),
941 ..onto("main")
942 })
943 .unwrap();
944 let sc = push.commit;
945 assert_eq!(sc.branch, "main");
946 assert_eq!(sc.tags, ["t"]);
947 assert_eq!(sc.bind_refs, ["b"]);
948 assert!(sc.orphan);
949 assert_eq!((sc.subject.as_str(), sc.body.as_str()), ("s", "m"));
950 let v = |value: &Value| ostrya_core::to_bytes(&Type::Variant, value).unwrap();
951 assert_eq!(
952 sc.metadata,
953 [
954 ("z".to_owned(), v(&string("1"))),
955 ("a".to_owned(), v(&string("2")))
956 ]
957 );
958 assert_eq!(sc.timestamp, Some(42));
959 let (_, push) = Prepared::new(TreePushOptions {
960 timestamp: None,
961 ..onto("main")
962 })
963 .unwrap();
964 assert_eq!(push.commit.timestamp, None);
965 assert_eq!(push.commit.subject, "");
966 }
967
968 #[test]
969 fn a_tag_that_the_server_holds_is_ref_mismatch() {
970 use crate::proto::{Encoding, RefState};
971 let tip = Checksum::from_bytes([5; 32]);
972 let server = ServerInfo {
973 version: 1,
974 mode: "archive".into(),
975 collection_id: None,
976 max_frame: 1 << 20,
977 max_have: 16_384,
978 encodings: vec![Encoding::Raw],
979 parallel_uploads: 1,
980 refs: [("main", Some(tip)), ("a", None), ("b", Some(tip))]
981 .into_iter()
982 .map(|(name, commit)| RefState {
983 name: name.into(),
984 commit,
985 })
986 .collect(),
987 };
988 check_tags_absent(&server, &strings(&["a"])).unwrap();
989 match check_tags_absent(&server, &strings(&["a", "b"])) {
990 Err(Error::RefMismatch { name, current, .. }) => {
991 assert_eq!(name, "b");
992 assert_eq!(current, Some(tip));
993 }
994 other => panic!("{other:?}"),
995 }
996 }
997
998 /// `scan_tree` refuses a metadata value that a commit cannot hold before
999 /// the walk, and gives the commit the root checksums of the model.
1000 #[test]
1001 fn scan_tree_checks_the_depth_and_fills_the_roots() {
1002 let root =
1003 std::env::temp_dir().join(format!("ostrya-remote-scan-tree-{}", std::process::id()));
1004 let _ = std::fs::remove_dir_all(&root);
1005 std::fs::create_dir_all(root.join("dir")).unwrap();
1006 std::fs::write(root.join("dir/file"), b"file").unwrap();
1007 let deep = (0..126).fold(Value::Byte(1), |value, _| {
1008 Value::Maybe(Some(Box::new(value)))
1009 });
1010 let ty = (0..126).fold(Type::Byte, |ty, _| Type::maybe(ty));
1011 let absent = root.join("absent");
1012 // The walk root is absent, so a refusal shows that the check runs
1013 // before the walk.
1014 match ostrya_rt::block_on(scan_tree(
1015 &absent,
1016 TreePushOptions {
1017 metadata: vec![("deep".into(), Value::variant(ty, deep))],
1018 ..onto("main")
1019 },
1020 )) {
1021 Err(Error::InvalidInput(m)) => assert!(m.contains("cannot hold"), "{m}"),
1022 other => panic!("{:?}", other.map(|_| ())),
1023 }
1024 let scanned = ostrya_rt::block_on(scan_tree(
1025 &root,
1026 TreePushOptions {
1027 collection: Some("org.example.A".into()),
1028 compression: Compression::Deflate { level: 3 },
1029 ..onto("main")
1030 },
1031 ));
1032 let _ = std::fs::remove_dir_all(&root);
1033 let scanned = scanned.unwrap();
1034 assert_eq!(scanned.commit.root_dirtree, scanned.model.root_dirtree());
1035 assert_eq!(scanned.commit.root_dirmeta, scanned.model.root_dirmeta());
1036 assert_eq!(scanned.commit.branch, "@org.example.A:main");
1037 assert_eq!(scanned.commit.timestamp, Some(1));
1038 assert_eq!(scanned.branch, Ref::collection("org.example.A", "main"));
1039 assert!(scanned.tags.is_empty());
1040 assert_eq!(scanned.compression, Compression::Deflate { level: 3 });
1041 // Two dirtrees, one dirmeta that the two directories share, and the
1042 // file.
1043 assert_eq!(scanned.model.object_names().len(), 4);
1044 }
1045
1046 /// On a reused handle, the filter sees `Scanning` for each entry. The
1047 /// hook gets one call with `Scanning` before the walk, and one call with
1048 /// `Hashing` after it.
1049 #[test]
1050 fn the_scan_shows_scanning_during_the_walk_and_hashing_after_it() {
1051 use std::sync::{Arc, Mutex};
1052
1053 use crate::PushPhase;
1054 use crate::tree::EntryAction;
1055
1056 /// One call to the hook or to the entry filter, in the order of the
1057 /// calls.
1058 #[derive(Debug, PartialEq, Eq)]
1059 enum Call {
1060 Hook(PushPhase),
1061 Filter,
1062 }
1063
1064 let root =
1065 std::env::temp_dir().join(format!("ostrya-remote-scan-phases-{}", std::process::id()));
1066 let _ = std::fs::remove_dir_all(&root);
1067 std::fs::create_dir_all(root.join("dir")).unwrap();
1068 std::fs::write(root.join("dir/file"), b"file").unwrap();
1069 let calls: Arc<Mutex<Vec<Call>>> = Arc::default();
1070 let hook_calls = Arc::clone(&calls);
1071 // A reused handle holds the phase of an earlier push.
1072 let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
1073 hook_calls.lock().unwrap().push(Call::Hook(snapshot.phase));
1074 }));
1075 progress.set_phase(PushPhase::Committing);
1076 calls.lock().unwrap().clear();
1077 let seen = Arc::new(Mutex::new(Vec::new()));
1078 let record = (seen.clone(), progress.clone(), Arc::clone(&calls));
1079 let filter: EntryFilter = Box::new(move |_path, _meta| {
1080 record.0.lock().unwrap().push(record.1.snapshot().phase);
1081 record.2.lock().unwrap().push(Call::Filter);
1082 EntryAction::Keep
1083 });
1084 let scan = ScanOptions {
1085 entry_filter: Some(filter),
1086 hash_jobs: None,
1087 };
1088 let model = ostrya_rt::block_on(TreeModel::scan_with(&root, scan, Some(&progress)));
1089 let _ = std::fs::remove_dir_all(&root);
1090 model.unwrap();
1091 let seen = seen.lock().unwrap();
1092 assert_eq!(seen.len(), 3, "{seen:?}");
1093 assert!(seen.iter().all(|p| *p == PushPhase::Scanning), "{seen:?}");
1094 assert_eq!(progress.snapshot().phase, PushPhase::Hashing);
1095 assert_eq!(
1096 *calls.lock().unwrap(),
1097 [
1098 Call::Hook(PushPhase::Scanning),
1099 Call::Filter,
1100 Call::Filter,
1101 Call::Filter,
1102 Call::Hook(PushPhase::Hashing),
1103 ]
1104 );
1105 }
1106
1107 /// The hook of a new handle gets one call with `Scanning` before the
1108 /// filter sees the first entry, and one call with `Hashing` after the
1109 /// filter sees the last entry.
1110 #[test]
1111 fn a_new_handle_gets_a_scanning_call_before_the_walk_and_a_hashing_call_after_it() {
1112 use std::sync::{Arc, Mutex};
1113
1114 use crate::PushPhase;
1115 use crate::tree::EntryAction;
1116
1117 /// One call to the hook or to the entry filter, in the order of the
1118 /// calls.
1119 #[derive(Debug, PartialEq, Eq)]
1120 enum Call {
1121 Hook(PushPhase),
1122 Filter,
1123 }
1124
1125 let root =
1126 std::env::temp_dir().join(format!("ostrya-remote-scan-hook-{}", std::process::id()));
1127 let _ = std::fs::remove_dir_all(&root);
1128 std::fs::create_dir_all(root.join("dir")).unwrap();
1129 std::fs::write(root.join("dir/file"), b"file").unwrap();
1130 let calls: Arc<Mutex<Vec<Call>>> = Arc::default();
1131 let hook_calls = Arc::clone(&calls);
1132 // A new handle holds the phase `Scanning`.
1133 let progress = PushProgress::with_hook(Arc::new(move |snapshot| {
1134 hook_calls.lock().unwrap().push(Call::Hook(snapshot.phase));
1135 }));
1136 let filter_calls = Arc::clone(&calls);
1137 let filter: EntryFilter = Box::new(move |_path, _meta| {
1138 filter_calls.lock().unwrap().push(Call::Filter);
1139 EntryAction::Keep
1140 });
1141 let scan = ScanOptions {
1142 entry_filter: Some(filter),
1143 hash_jobs: None,
1144 };
1145 let model = ostrya_rt::block_on(TreeModel::scan_with(&root, scan, Some(&progress)));
1146 let _ = std::fs::remove_dir_all(&root);
1147 model.unwrap();
1148 // The filter sees the root, `dir`, and `dir/file`.
1149 assert_eq!(
1150 *calls.lock().unwrap(),
1151 [
1152 Call::Hook(PushPhase::Scanning),
1153 Call::Filter,
1154 Call::Filter,
1155 Call::Filter,
1156 Call::Hook(PushPhase::Hashing),
1157 ]
1158 );
1159 }
1160}