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, 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 longest collection id, in bytes. The server writes the refs of a
21/// collection under one directory of that name.
22const MAX_COLLECTION_ID_LEN: usize = 255;
23
24/// The metadata keys of the bindings, which the server writes.
25const BINDING_KEYS: [&str; 2] = ["ostree.ref-binding", "ostree.collection-binding"];
26
27/// The options of a tree push.
28///
29/// [`push_tree`], [`push_tree_prepared`], and [`push_tree_over_stream`] take
30/// them. The struct carries no `#[non_exhaustive]`. A caller builds it with
31/// `..Default::default()`.
32#[derive(Default)]
33pub struct TreePushOptions {
34 /// The branch of the server that the server moves to the new commit.
35 ///
36 /// The parent of the commit is the commit of the branch on the server
37 /// when the server writes the commit. If the branch is absent, the commit
38 /// has no parent.
39 pub onto: String,
40 /// The tags that the server creates at the new commit, in order.
41 ///
42 /// A tag that exists on the server refuses the push.
43 pub tags: Vec<String>,
44 /// The names that the commit binds and that get no ref, in order.
45 ///
46 /// The `ostree.ref-binding` of the commit holds the branch, each tag, and
47 /// each of these names.
48 pub bind_refs: Vec<String>,
49 /// The switch that makes a commit with no parent.
50 ///
51 /// On a branch that exists, the server allows it only for a client that
52 /// can also delete the branch.
53 pub orphan: bool,
54 /// The collection id of the namespace of the server that the push
55 /// writes.
56 ///
57 /// `None` writes the local refs of the server. The collection id of the
58 /// server also writes its local refs.
59 pub collection: Option<String>,
60 /// The subject of the commit, empty if not set.
61 pub subject: Option<String>,
62 /// The body of the commit, empty if not set.
63 pub body: Option<String>,
64 /// The entries of the `a{sv}` metadata dict of the commit, in order.
65 ///
66 /// Each value is a variant. The server writes the bindings after the
67 /// entries.
68 pub metadata: Vec<(String, Value)>,
69 /// The timestamp of the commit, in seconds since the Unix epoch, UTC.
70 ///
71 /// If this field is not set, the server takes its clock. The push reads
72 /// no environment variable.
73 pub timestamp: Option<u64>,
74 /// The encoding of the content objects.
75 pub compression: Compression,
76 /// The filter that sees each entry of the walk.
77 pub entry_filter: Option<EntryFilter>,
78 /// The maximum number of regular files that the hash pass reads at one
79 /// time.
80 ///
81 /// [`ScanOptions::hash_jobs`] gives the default and the limits.
82 pub hash_jobs: Option<usize>,
83 /// The progress handle of the scan and of the session.
84 ///
85 /// The scan sets its phases in the handle, and the session counts its
86 /// progress into it.
87 pub progress: Option<PushProgress>,
88}
89
90/// Pushes the directory `root` to `endpoint` as one server commit.
91///
92/// The server makes the commit over the tree, moves the branch to it, and
93/// creates each tag at it, in one transaction. The push runs in this order:
94///
95/// 1. It checks `opts` and refuses each value that [`push_tree_over_stream`]
96/// refuses. Then it makes the transport ready with
97/// [`PushSession::prepare`]. For ssh, it builds the command line. For
98/// HTTP, it builds the HTTP client.
99/// 2. It walks and hashes the tree with [`TreeModel::scan`], with
100/// `entry_filter` and `hash_jobs`.
101/// 3. It starts the ssh client, or sends the first HTTP request. It opens the
102/// session with the branch and the tags in one `Hello`.
103/// 4. It offers each object of the tree in one round of `Have`. It sends the
104/// objects that the server lacks, and then it sends `Commit` with the
105/// server commit.
106///
107/// A refusal of the options, a walk error, and a hash error start no ssh
108/// client, send no request, and open no session. [`push_tree_over_stream`]
109/// gives the rules of the server commit and of the session.
110///
111/// [`PushStats::elapsed`](crate::session::PushStats::elapsed) of the outcome
112/// covers the session alone, from the open of the session. It excludes the
113/// time of the scan.
114///
115/// Under the tokio backend, the call must run within a runtime that has the
116/// IO driver and the time driver enabled, as [`PushSession::connect`] states.
117///
118/// # Errors
119///
120/// - Each error of [`push_tree_prepared`](push_tree_prepared#errors).
121/// - [`Error::InvalidInput`] if the ssh command or the receive command is
122/// empty or holds only white space, or if the value of `OSTRYA_SSH_COMMAND`
123/// is not UTF-8. The [empty values](crate::SshOptions#empty-values) give
124/// the full rule.
125/// - [`Error::InvalidInput`] if the options of an HTTP endpoint do not name
126/// exactly one mirror, or if
127/// [`check_base_url`](ostrya_fetch::check_base_url) refuses the mirror.
128/// - [`Error::Fetch`] if [`Fetcher::new`](ostrya_fetch::Fetcher::new) refuses
129/// the options of an HTTP endpoint, for example a credential to an
130/// `http://` address without `allow_cleartext_credentials`.
131///
132/// [`Error::InvalidInput`]: crate::Error::InvalidInput
133/// [`Error::Fetch`]: crate::Error::Fetch
134pub async fn push_tree(
135 endpoint: Endpoint,
136 root: &Path,
137 opts: TreePushOptions,
138) -> Result<PushOutcome> {
139 let (scan, push) = Prepared::new(opts)?;
140 let transport = PushSession::prepare(endpoint).await?;
141 push.scan_and_run(transport, root, scan).await
142}
143
144/// Pushes the directory `root` as one server commit over a prepared
145/// transport.
146///
147/// `session` is a transport that [`PushSession::prepare`] made ready. The
148/// push is that of [`push_tree`] with the transport checks done first, so a
149/// caller can do them before the work that builds `opts`. For example, the
150/// caller can read a large body file after the checks.
151///
152/// The push checks `opts` as [`push_tree`] does, then scans the tree, and then
153/// opens `session`. A refusal of the options, a walk error, and a hash error
154/// start no ssh client, send no request, and open no session. The other rules
155/// are those of [`push_tree`].
156///
157/// # Errors
158///
159/// - Each error of [`push_tree_over_stream`](push_tree_over_stream#errors).
160/// - [`Error::Transport`] if the ssh client cannot be started, or if it exits
161/// with a failure status after the session fails with an I/O error.
162/// - [`Error::Transport`] if an HTTP server answers with a status that the
163/// receive endpoint does not give, or with a body that is not one frame.
164/// - [`Error::Unauthorized`] if an HTTP server refuses the credential of the
165/// session with an `Error` message of the code `unauthorized`.
166/// - [`Error::Fetch`] for a failure of the HTTP client.
167///
168/// [`Error::Transport`]: crate::Error::Transport
169/// [`Error::Unauthorized`]: crate::Error::Unauthorized
170/// [`Error::Fetch`]: crate::Error::Fetch
171pub async fn push_tree_prepared(
172 session: PreparedSession,
173 root: &Path,
174 opts: TreePushOptions,
175) -> Result<PushOutcome> {
176 let (scan, push) = Prepared::new(opts)?;
177 push.scan_and_run(session, root, scan).await
178}
179
180/// Pushes the directory `root` as one server commit over a pair of byte
181/// streams.
182///
183/// `input` comes from the server, and `output` goes to it. The push scans
184/// the tree before it writes the first byte to `output`.
185///
186/// # Refusals
187///
188/// Before the scan, the push refuses these values of `opts`:
189///
190/// - a branch or a tag that holds `:`, that fails the ref-name rule of
191/// [`is_ref_name`](ostrya_core::is_ref_name), for example a name that holds
192/// `^`, or that is 64 lowercase hex characters, which a revision reads as
193/// a commit checksum
194/// - a tag that is the branch, and a tag named twice
195/// - a bound name that holds `:` or that fails the ref-name rule
196/// - a `collection` that fails
197/// [`is_collection_id`](ostrya_core::is_collection_id) or is longer than
198/// 255 bytes
199/// - a DEFLATE level outside 1 through 9
200/// - an empty key in `metadata`, the key `ostree.ref-binding` or
201/// `ostree.collection-binding`, which the server writes, and a value that
202/// is not a variant
203///
204/// The scan refuses `hash_jobs` of `Some(0)` before the walk starts. If the
205/// push refuses a value, or if the walk or the hash pass fails, the push
206/// writes nothing.
207///
208/// # Server commit
209///
210/// The session opens with the branch and then each tag. The push sends
211/// [`collection`](TreePushOptions::collection) in `Hello`. After `HelloReply`,
212/// the push refuses a tag that the server holds with
213/// [`Error::RefMismatch`]. Then it runs
214/// [`PushSession::check_server_commit`]: a commit must hold each metadata
215/// value, and the `Commit` frame of the server commit and the longest
216/// `CommitReply` must fit in the `max-frame` of the server. Each refusal
217/// comes before the push offers an object.
218///
219/// The push offers each object of the tree in one round of `Have`, and sends
220/// the objects that the server lacks. It sends no commit object and no
221/// detached metadata. Then it sends the server commit with the root dirtree
222/// and the root dirmeta of the tree, the subject, the body, the entries of
223/// `metadata`, the timestamp, the tags, the bound names, and `orphan`.
224///
225/// The server reads the tip of the branch and writes the commit with that tip
226/// as its parent, the bindings of its namespace, and the keys of its own
227/// signing rule. [`PushOutcome::commit`] holds the commit that the server
228/// wrote.
229///
230/// The server verifies each object. If the bytes of a file change after the
231/// hash pass, the server sends an `Error` message and no ref changes.
232///
233/// # Failures
234///
235/// A failure after the session opens and before `Commit` ends the session, and
236/// the push returns that failure. If the stream is still usable, the push
237/// writes `Abort`. Over HTTP, the push ends the session with `DELETE`.
238/// [`PushStats::elapsed`](crate::session::PushStats::elapsed)
239/// covers the session alone.
240///
241/// # Errors
242///
243/// - [`Error::InvalidInput`] for each value of [Refusals](#refusals), and if
244/// `hash_jobs` is `Some(0)`.
245/// - [`Error::Walk`] if the walk or the hash pass fails. [`TreeModel::scan`]
246/// gives the `io::ErrorKind` of each case.
247/// - [`Error::RefMismatch`] if `HelloReply` reports a commit for a tag.
248/// - [`Error::InvalidInput`] if a commit cannot hold a value of `metadata`.
249/// In a commit, a value can hold two levels of containers fewer than a
250/// variant.
251/// - [`Error::LimitExceeded`] if the `Commit` frame of the server commit, or
252/// the longest `CommitReply` to it, is over the `max-frame` of the
253/// server.
254/// - [`Error::Source`] if the send pass cannot open or read a file of the
255/// tree. The error of a failed open is the [`Error::Walk`] of that file.
256/// - [`Error::Protocol`] or [`Error::LimitExceeded`] if the codec refuses a
257/// frame of the session.
258/// - [`Error::Io`] for an I/O error of `input` or `output`.
259/// - [`Error::CommitOutcomeUnknown`] if the session ends after `Commit` with
260/// no reply that the client can read.
261/// - An `Error` message from the server, as the [`Error`] variant of its code.
262/// An example is [`Error::RefDenied`] if the client has no `c` on the
263/// branch, or if the server runs hooks, which take no server commit.
264///
265/// [`Error`]: crate::Error
266/// [`Error::InvalidInput`]: crate::Error::InvalidInput
267/// [`Error::Walk`]: crate::Error::Walk
268/// [`Error::RefMismatch`]: crate::Error::RefMismatch
269/// [`Error::LimitExceeded`]: crate::Error::LimitExceeded
270/// [`Error::Source`]: crate::Error::Source
271/// [`Error::Protocol`]: crate::Error::Protocol
272/// [`Error::Io`]: crate::Error::Io
273/// [`Error::CommitOutcomeUnknown`]: crate::Error::CommitOutcomeUnknown
274/// [`Error::RefDenied`]: crate::Error::RefDenied
275pub async fn push_tree_over_stream<R, W>(
276 input: R,
277 output: W,
278 root: &Path,
279 opts: TreePushOptions,
280) -> Result<PushOutcome>
281where
282 R: AsyncRead + Unpin + Send + 'static,
283 W: AsyncWrite + Unpin + Send + 'static,
284{
285 let (scan, push) = Prepared::new(opts)?;
286 let model = push.scan(root, scan).await?;
287 let session =
288 PushSession::over_stream(input, output, &push.refs, push.session_options()).await?;
289 push.run(session, model).await
290}
291
292/// The checked options of a tree push, without the options of the scan.
293struct Prepared {
294 /// The refs of `Hello`: the branch, then each tag.
295 refs: Vec<String>,
296 /// The server commit, with no root checksums before the scan.
297 commit: ServerCommit,
298 collection: Option<String>,
299 compression: Compression,
300 progress: Option<PushProgress>,
301}
302
303impl Prepared {
304 /// Checks `opts`. Returns the options of the scan as a separate value,
305 /// because the entry filter is not `Sync`.
306 fn new(opts: TreePushOptions) -> Result<(ScanOptions, Prepared)> {
307 let TreePushOptions {
308 onto,
309 tags,
310 bind_refs,
311 orphan,
312 collection,
313 subject,
314 body,
315 metadata,
316 timestamp,
317 compression,
318 entry_filter,
319 hash_jobs,
320 progress,
321 } = opts;
322 check_names(&onto, &tags, &bind_refs)?;
323 if let Some(id) = &collection {
324 check_collection(id)?;
325 }
326 deflate_level(compression)?;
327 let metadata = metadata_entries(metadata)?;
328 let scan = ScanOptions {
329 entry_filter,
330 hash_jobs,
331 };
332 let refs = std::iter::once(onto.clone())
333 .chain(tags.iter().cloned())
334 .collect();
335 // The scan gives the root checksums.
336 let unset = Checksum::from_bytes([0; 32]);
337 let push = Prepared {
338 refs,
339 commit: ServerCommit {
340 branch: onto,
341 tags,
342 bind_refs,
343 root_dirtree: unset,
344 root_dirmeta: unset,
345 subject: subject.unwrap_or_default(),
346 body: body.unwrap_or_default(),
347 metadata,
348 timestamp,
349 orphan,
350 },
351 collection,
352 compression,
353 progress,
354 };
355 Ok((scan, push))
356 }
357
358 /// Walks and hashes the tree at `root`, and sets the phases of the scan
359 /// in the progress handle.
360 async fn scan(&self, root: &Path, scan: ScanOptions) -> Result<TreeModel> {
361 TreeModel::scan_with(root, scan, self.progress.as_ref()).await
362 }
363
364 /// Scans the tree at `root`, opens `transport`, and runs the push.
365 async fn scan_and_run(
366 self,
367 transport: PreparedSession,
368 root: &Path,
369 scan: ScanOptions,
370 ) -> Result<PushOutcome> {
371 let model = self.scan(root, scan).await?;
372 let session = transport.open(&self.refs, self.session_options()).await?;
373 // The future of the run is large. The box keeps it out of the future
374 // of the push.
375 Box::pin(self.run(session, model)).await
376 }
377
378 fn session_options(&self) -> SessionOptions {
379 SessionOptions {
380 collection: self.collection.clone(),
381 progress: self.progress.clone(),
382 ..SessionOptions::default()
383 }
384 }
385
386 /// Runs the push over `session`. A failure before `Commit` ends the
387 /// session, with `Abort` if the stream is still usable.
388 async fn run(self, session: PushSession, model: TreeModel) -> Result<PushOutcome> {
389 let mut commit = self.commit;
390 commit.root_dirtree = model.root_dirtree();
391 commit.root_dirmeta = model.root_dirmeta();
392 match upload(&session, &model, &commit, self.compression).await {
393 Ok(()) => {
394 drop(model);
395 session.server_commit(commit).await
396 }
397 Err(e) => {
398 let _ = session.abort().await;
399 Err(e)
400 }
401 }
402 }
403}
404
405/// Runs the checks after `HelloReply`, the one `Have` round, and the upload
406/// of the objects of `model` that the server lacks.
407async fn upload(
408 session: &PushSession,
409 model: &TreeModel,
410 commit: &ServerCommit,
411 compression: Compression,
412) -> Result<()> {
413 check_tags_absent(session.server(), &commit.tags)?;
414 session.check_server_commit(commit)?;
415 let names = model.object_names();
416 let missing = session.missing(&names).await?;
417 drop(names);
418 session.send(model, &missing, &[], compression).await
419}
420
421/// Refuses a tag that `server` reports at a commit, with
422/// [`Error::RefMismatch`]. The server refuses it at `Commit` too.
423fn check_tags_absent(server: &ServerInfo, tags: &[String]) -> Result<()> {
424 match tags
425 .iter()
426 .find_map(|tag| server.tip(tag).map(|tip| (tag, tip)))
427 {
428 Some((tag, current)) => Err(Error::RefMismatch {
429 message: format!("ref '{tag}' is at {current}"),
430 name: tag.clone(),
431 current: Some(current),
432 }),
433 None => Ok(()),
434 }
435}
436
437/// Refuses a name of a ref that the server commit writes: a name that holds
438/// `:`, a name that fails the ref-name rule (which includes a name that holds
439/// `^`), and a name of 64 lowercase hex characters. `what` names the ref in
440/// the message.
441fn check_ref(name: &str, what: &str) -> Result<()> {
442 if name.contains(':') {
443 return Err(invalid(format!(
444 "{what} '{name}' holds ':'; a tree push writes refs below refs/heads"
445 )));
446 }
447 if !ostrya_core::is_ref_name(name) {
448 return Err(invalid(format!("{what} '{name}' is not a valid ref name")));
449 }
450 if ostrya_core::is_checksum_shaped(name) {
451 return Err(invalid(format!(
452 "{what} '{name}' is 64 hex characters, which a revision reads as a commit checksum"
453 )));
454 }
455 Ok(())
456}
457
458/// Refuses a bad branch, a bad tag, a tag that is the branch, a tag named
459/// twice, and a bound name that holds `:` or fails the ref-name rule.
460fn check_names(onto: &str, tags: &[String], bind_refs: &[String]) -> Result<()> {
461 check_ref(onto, "branch")?;
462 let mut seen = HashSet::new();
463 for tag in tags {
464 check_ref(tag, "tag")?;
465 if tag == onto {
466 return Err(invalid(format!("the tag '{tag}' is also the branch")));
467 }
468 if !seen.insert(tag.as_str()) {
469 return Err(invalid(format!("the tag '{tag}' is named twice")));
470 }
471 }
472 for name in bind_refs {
473 if name.contains(':') || !ostrya_core::is_ref_name(name) {
474 return Err(invalid(format!(
475 "bound name '{name}' is not a valid ref name"
476 )));
477 }
478 }
479 Ok(())
480}
481
482/// Refuses a collection id that fails the collection-id rule or is longer
483/// than [`MAX_COLLECTION_ID_LEN`] bytes.
484fn check_collection(id: &str) -> Result<()> {
485 if id.len() > MAX_COLLECTION_ID_LEN {
486 return Err(invalid(format!(
487 "the collection id of {} bytes is longer than {MAX_COLLECTION_ID_LEN} bytes",
488 id.len()
489 )));
490 }
491 if !ostrya_core::is_collection_id(id) {
492 return Err(invalid(format!("invalid collection id '{id}'")));
493 }
494 Ok(())
495}
496
497/// Returns the metadata entries of a server commit: each key with the bytes of
498/// its value as a `v` in normal form, in order.
499///
500/// An empty key, a binding key, and a value that is not a variant are
501/// [`Error::InvalidInput`].
502fn metadata_entries(entries: Vec<(String, Value)>) -> Result<Vec<(String, Vec<u8>)>> {
503 entries
504 .into_iter()
505 .map(|(key, value)| {
506 if key.is_empty() {
507 return Err(invalid("the metadata holds an empty key"));
508 }
509 if BINDING_KEYS.contains(&key.as_str()) {
510 return Err(invalid(format!(
511 "the metadata holds the key '{key}', which the server writes"
512 )));
513 }
514 let bytes = ostrya_core::to_bytes(&Type::Variant, &value).map_err(|e| {
515 invalid(format!(
516 "the metadata value under '{key}' is not a variant: {e}"
517 ))
518 })?;
519 Ok((key, bytes))
520 })
521 .collect()
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527
528 fn refused(opts: TreePushOptions) -> String {
529 match Prepared::new(opts) {
530 Err(Error::InvalidInput(m)) => m,
531 Err(e) => panic!("{e:?}"),
532 Ok(_) => panic!("accepted"),
533 }
534 }
535
536 fn onto(branch: &str) -> TreePushOptions {
537 TreePushOptions {
538 onto: branch.into(),
539 timestamp: Some(1),
540 ..Default::default()
541 }
542 }
543
544 fn strings(items: &[&str]) -> Vec<String> {
545 items.iter().map(|s| s.to_string()).collect()
546 }
547
548 const BAD_NAMES: [&str; 16] = [
549 "", "main^", "a^b", "^", "x/y^", "/a", "a/", "a//b", ".", "..", "a/../b", "a\0b", "a b",
550 "a*", "-a", "a/.b",
551 ];
552
553 #[test]
554 fn the_branch_and_the_tags_are_checked_before_the_scan() {
555 let hex = "ab".repeat(32);
556 for (what, make) in [
557 (
558 "branch",
559 (|name: &str| onto(name)) as fn(&str) -> TreePushOptions,
560 ),
561 ("tag", |name: &str| TreePushOptions {
562 tags: strings(&[name]),
563 ..onto("main")
564 }),
565 ] {
566 assert!(refused(make("origin:main")).contains("':'"), "{what}");
567 for bad in BAD_NAMES {
568 let m = refused(make(bad));
569 assert!(m.contains("not a valid ref name"), "{what} {bad:?}: {m}");
570 assert!(m.starts_with(what), "{what} {bad:?}: {m}");
571 }
572 assert!(refused(make(&hex)).contains("commit checksum"), "{what}");
573 }
574 let m = refused(TreePushOptions {
575 tags: strings(&["t", "main"]),
576 ..onto("main")
577 });
578 assert!(m.contains("'main' is also the branch"), "{m}");
579 let m = refused(TreePushOptions {
580 tags: strings(&["t", "u", "t"]),
581 ..onto("main")
582 });
583 assert!(m.contains("'t' is named twice"), "{m}");
584 let (_, push) = Prepared::new(TreePushOptions {
585 tags: strings(&["a/b", "x.y", &hex.to_uppercase(), &hex[1..]]),
586 ..onto("main")
587 })
588 .unwrap();
589 assert_eq!(
590 push.refs,
591 ["main", "a/b", "x.y", &hex.to_uppercase(), &hex[1..]]
592 );
593 }
594
595 #[test]
596 fn a_bound_name_passes_the_ref_name_rule_with_no_colon() {
597 for bad in BAD_NAMES.iter().copied().chain(["o:main"]) {
598 let m = refused(TreePushOptions {
599 bind_refs: strings(&[bad]),
600 ..onto("main")
601 });
602 assert!(m.contains("bound name"), "{bad:?}: {m}");
603 }
604 // A bound name can repeat, can be the branch, and can be 64 hex
605 // characters, because it gets no ref.
606 let hex = "ab".repeat(32);
607 let (_, push) = Prepared::new(TreePushOptions {
608 bind_refs: strings(&["x", "x", "main", &hex]),
609 ..onto("main")
610 })
611 .unwrap();
612 assert_eq!(push.commit.bind_refs, ["x", "x", "main", hex.as_str()]);
613 assert_eq!(push.refs, ["main"]);
614 }
615
616 #[test]
617 fn the_collection_is_checked_before_the_scan() {
618 let longest = format!("org.{}", "a".repeat(251));
619 let over = format!("org.{}", "a".repeat(252));
620 for (id, needle) in [("no-dot", "invalid collection id"), (&*over, "256 bytes")] {
621 let m = refused(TreePushOptions {
622 collection: Some(id.into()),
623 ..onto("main")
624 });
625 assert!(m.contains(needle), "{m}");
626 }
627 let (_, push) = Prepared::new(TreePushOptions {
628 collection: Some(longest.clone()),
629 ..onto("main")
630 })
631 .unwrap();
632 assert_eq!(push.session_options().collection, Some(longest));
633 }
634
635 #[test]
636 fn the_other_options_are_checked_before_the_scan() {
637 for level in [0, 10] {
638 let m = refused(TreePushOptions {
639 compression: Compression::Deflate { level },
640 ..onto("main")
641 });
642 assert!(m.contains("compression level"), "{m}");
643 }
644 let variant = Value::variant(ostrya_core::Type::Str, Value::Str("v".into()));
645 let m = refused(TreePushOptions {
646 metadata: vec![(String::new(), variant.clone())],
647 ..onto("main")
648 });
649 assert!(m.contains("metadata holds an empty key"), "{m}");
650 for key in BINDING_KEYS {
651 let m = refused(TreePushOptions {
652 metadata: vec![("k".into(), variant.clone()), (key.into(), variant.clone())],
653 ..onto("main")
654 });
655 assert!(
656 m.contains(&format!("'{key}', which the server writes")),
657 "{m}"
658 );
659 }
660 let m = refused(TreePushOptions {
661 metadata: vec![("k".into(), Value::Str("bare".into()))],
662 ..onto("main")
663 });
664 assert!(m.contains("not a variant"), "{m}");
665 }
666
667 #[test]
668 fn the_server_commit_carries_the_options() {
669 let string = |s: &str| Value::variant(ostrya_core::Type::Str, Value::Str(s.into()));
670 let (_, push) = Prepared::new(TreePushOptions {
671 tags: strings(&["t"]),
672 bind_refs: strings(&["b"]),
673 orphan: true,
674 subject: Some("s".into()),
675 body: Some("m".into()),
676 metadata: vec![("z".into(), string("1")), ("a".into(), string("2"))],
677 timestamp: Some(42),
678 ..onto("main")
679 })
680 .unwrap();
681 let sc = push.commit;
682 assert_eq!(sc.branch, "main");
683 assert_eq!(sc.tags, ["t"]);
684 assert_eq!(sc.bind_refs, ["b"]);
685 assert!(sc.orphan);
686 assert_eq!((sc.subject.as_str(), sc.body.as_str()), ("s", "m"));
687 let v = |value: &Value| ostrya_core::to_bytes(&Type::Variant, value).unwrap();
688 assert_eq!(
689 sc.metadata,
690 [
691 ("z".to_owned(), v(&string("1"))),
692 ("a".to_owned(), v(&string("2")))
693 ]
694 );
695 assert_eq!(sc.timestamp, Some(42));
696 let (_, push) = Prepared::new(TreePushOptions {
697 timestamp: None,
698 ..onto("main")
699 })
700 .unwrap();
701 assert_eq!(push.commit.timestamp, None);
702 assert_eq!(push.commit.subject, "");
703 }
704
705 #[test]
706 fn a_tag_that_the_server_holds_is_ref_mismatch() {
707 use crate::proto::{Encoding, RefState};
708 let tip = Checksum::from_bytes([5; 32]);
709 let server = ServerInfo {
710 version: 1,
711 mode: "archive".into(),
712 collection_id: None,
713 collection: None,
714 max_frame: 1 << 20,
715 max_have: 16_384,
716 encodings: vec![Encoding::Raw],
717 parallel_uploads: 1,
718 refs: [("main", Some(tip)), ("a", None), ("b", Some(tip))]
719 .into_iter()
720 .map(|(name, commit)| RefState {
721 name: name.into(),
722 commit,
723 })
724 .collect(),
725 };
726 check_tags_absent(&server, &strings(&["a"])).unwrap();
727 match check_tags_absent(&server, &strings(&["a", "b"])) {
728 Err(Error::RefMismatch { name, current, .. }) => {
729 assert_eq!(name, "b");
730 assert_eq!(current, Some(tip));
731 }
732 other => panic!("{other:?}"),
733 }
734 }
735
736 #[test]
737 fn the_scan_shows_scanning_during_the_walk_and_hashing_after_it() {
738 use std::sync::{Arc, Mutex};
739
740 use crate::PushPhase;
741 use crate::tree::EntryAction;
742
743 let root =
744 std::env::temp_dir().join(format!("ostrya-remote-scan-phases-{}", std::process::id()));
745 let _ = std::fs::remove_dir_all(&root);
746 std::fs::create_dir_all(root.join("dir")).unwrap();
747 std::fs::write(root.join("dir/file"), b"file").unwrap();
748 // A reused handle holds the phase of an earlier push.
749 let progress = PushProgress::new();
750 progress.set_phase(PushPhase::Committing);
751 let seen = Arc::new(Mutex::new(Vec::new()));
752 let record = (seen.clone(), progress.clone());
753 let filter: EntryFilter = Box::new(move |_path, _meta| {
754 record.0.lock().unwrap().push(record.1.snapshot().phase);
755 EntryAction::Keep
756 });
757 let scan = ScanOptions {
758 entry_filter: Some(filter),
759 hash_jobs: None,
760 };
761 let model = ostrya_rt::block_on(TreeModel::scan_with(&root, scan, Some(&progress)));
762 let _ = std::fs::remove_dir_all(&root);
763 model.unwrap();
764 let seen = seen.lock().unwrap();
765 assert_eq!(seen.len(), 3, "{seen:?}");
766 assert!(seen.iter().all(|p| *p == PushPhase::Scanning), "{seen:?}");
767 assert_eq!(progress.snapshot().phase, PushPhase::Hashing);
768 }
769}