1use crate::delete::LinkChildOutcomes;
2use anyhow::{Context, anyhow};
3use async_recursion::async_recursion;
4use std::sync::Arc;
5use tracing::instrument;
6
7use crate::copy;
8use crate::copy::{
9 EmptyDirAction, Settings as CopySettings, Summary as CopySummary, check_empty_dir_cleanup,
10};
11use crate::filecmp;
12use crate::preserve;
13use crate::progress;
14use crate::safedir::{self, Dir, Handle};
15use crate::walk::{
16 self, AdmittedEntry, AdmittedLeaf, EntryAdmission, EntryKind, LeafPermit, PermitKind,
17};
18
19pub type Error = crate::error::OperationError<Summary>;
22
23#[derive(Debug, Clone)]
24pub struct Settings {
25 pub copy_settings: CopySettings,
26 pub update_compare: filecmp::MetadataCmpSettings,
27 pub update_exclusive: bool,
28 pub filter: Option<crate::filter::FilterSettings>,
30 pub dry_run: Option<crate::config::DryRunMode>,
32 pub preserve: preserve::Settings,
34}
35
36#[derive(Copy, Clone, Debug, Eq, PartialEq)]
37enum UpdateRootRequirement {
38 Optional,
39 RequiredForDestructiveOperation,
40}
41
42impl UpdateRootRequirement {
43 fn from_settings(settings: &Settings) -> Self {
44 if settings.update_exclusive || settings.copy_settings.delete.is_some() {
45 Self::RequiredForDestructiveOperation
46 } else {
47 Self::Optional
48 }
49 }
50
51 fn is_required(self) -> bool {
52 self == Self::RequiredForDestructiveOperation
53 }
54
55 fn for_entry(self, rel_path: &std::path::Path) -> Self {
56 if rel_path.as_os_str().is_empty() {
57 self
58 } else {
59 Self::Optional
60 }
61 }
62
63 #[allow(clippy::result_large_err)]
64 fn classify<T>(
65 self,
66 result: std::io::Result<T>,
67 update_path: &std::path::Path,
68 ) -> Result<Option<T>, Error> {
69 match result {
70 Ok(value) => Ok(Some(value)),
71 Err(error) if error.kind() == std::io::ErrorKind::NotFound && !self.is_required() => {
72 Ok(None)
73 }
74 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
75 Err(missing_destructive_update_error(update_path))
76 }
77 Err(error) => Err(Error::new(
78 anyhow::Error::new(error)
79 .context(format!("failed reading metadata from {update_path:?}")),
80 Default::default(),
81 )),
82 }
83 }
84}
85
86fn missing_destructive_update_error(update_path: &std::path::Path) -> Error {
87 Error::new(
88 anyhow!(
89 "--update path {:?} does not exist (rejected under --delete or --update-exclusive to avoid silently pruning destination entries the update tree would otherwise have preserved)",
90 update_path
91 ),
92 Default::default(),
93 )
94}
95
96fn skipped_summary_for(kind: EntryKind) -> Summary {
100 let copy_summary = match kind {
101 EntryKind::Dir => CopySummary {
102 directories_skipped: 1,
103 ..Default::default()
104 },
105 EntryKind::Symlink => CopySummary {
106 symlinks_skipped: 1,
107 ..Default::default()
108 },
109 EntryKind::File | EntryKind::Special => CopySummary {
110 files_skipped: 1,
111 ..Default::default()
112 },
113 };
114 Summary {
115 copy_summary,
116 ..Default::default()
117 }
118}
119
120#[derive(Copy, Clone, Debug, Default)]
121pub struct Summary {
122 pub hard_links_created: usize,
123 pub hard_links_unchanged: usize,
124 pub copy_summary: CopySummary,
125}
126
127impl std::ops::Add for Summary {
128 type Output = Self;
129 fn add(self, other: Self) -> Self {
130 Self {
131 hard_links_created: self.hard_links_created + other.hard_links_created,
132 hard_links_unchanged: self.hard_links_unchanged + other.hard_links_unchanged,
133 copy_summary: self.copy_summary + other.copy_summary,
134 }
135 }
136}
137
138impl std::fmt::Display for Summary {
139 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
140 write!(
141 f,
142 "{}\n\
143 link:\n\
144 -----\n\
145 hard-links created: {}\n\
146 hard links unchanged: {}\n",
147 &self.copy_summary, self.hard_links_created, self.hard_links_unchanged
148 )
149 }
150}
151
152#[instrument(skip(prog_track, settings))]
173#[allow(clippy::too_many_arguments)]
174async fn hard_link_entry_fd(
175 prog_track: &'static progress::Progress,
176 src_handle: &crate::safedir::Handle,
177 dst_dir: &Arc<Dir>,
178 dst_name: &std::ffi::OsStr,
179 dst_path: &std::path::Path,
180 settings: &Settings,
181 destination: ©::DestinationContext,
182) -> Result<Summary, Error> {
183 let mut link_summary = Summary::default();
184 match dst_dir.hard_link_handle_at(src_handle, dst_name).await {
185 Ok(()) => {}
186 Err(error)
187 if settings.copy_settings.overwrite
188 && error.kind() == std::io::ErrorKind::AlreadyExists =>
189 {
190 tracing::debug!("'dst' already exists, check if we need to update");
191 let dst_handle = dst_dir
192 .child(dst_name)
193 .await
194 .with_context(|| format!("cannot read {dst_path:?} metadata"))
195 .map_err(|err| Error::new(err, Default::default()))?;
196 if dst_handle.kind() == src_handle.kind()
200 && dst_handle.dev() == src_handle.dev()
201 && dst_handle.ino() == src_handle.ino()
202 {
203 tracing::debug!("no change, leaving file as is");
204 prog_track.hard_links_unchanged.inc();
205 return Ok(Summary {
206 hard_links_unchanged: 1,
207 ..Default::default()
208 });
209 }
210 tracing::info!("'dst' file type changed, removing and hard-linking");
211 destination
213 .check_leaf_replacement_parent(dst_dir, dst_path)
214 .await
215 .map_err(|error| Error::new(error.into(), link_summary))?;
216 let rm_summary = copy::remove_existing_guarded(
217 prog_track,
218 dst_dir,
219 dst_name,
220 dst_path,
221 dst_handle.into_removal_snapshot(),
222 &settings.copy_settings,
223 Some(destination.protection()),
224 )
225 .await
226 .map_err(|err| {
227 link_summary.copy_summary.rm_summary = err.summary.rm_summary;
228 Error::new(err.source, link_summary)
229 })?;
230 link_summary.copy_summary.rm_summary = rm_summary;
231 dst_dir
232 .hard_link_handle_at(src_handle, dst_name)
233 .await
234 .with_context(|| format!("failed to hard link to {dst_path:?}"))
235 .map_err(|err| Error::new(err, link_summary))?;
236 }
237 Err(error) => {
238 return Err(Error::new(
239 anyhow::Error::from(error).context(format!("failed to hard link to {dst_path:?}")),
240 link_summary,
241 ));
242 }
243 }
244 prog_track.hard_links_created.inc();
245 link_summary.hard_links_created = 1;
246 Ok(link_summary)
247}
248
249#[instrument(skip(prog_track, settings))]
263pub async fn link(
264 prog_track: &'static progress::Progress,
265 cwd: &std::path::Path,
266 src: &std::path::Path,
267 dst: &std::path::Path,
268 update: &Option<std::path::PathBuf>,
269 settings: &Settings,
270 is_fresh: bool,
271) -> Result<Summary, Error> {
272 crate::task_scope::scope_tasks(link_inner(
273 prog_track, cwd, src, dst, update, settings, is_fresh,
274 ))
275 .await
276}
277
278#[cfg(test)]
279type AfterUpdatePrecheckHook = Box<dyn FnOnce() + Send>;
280
281#[cfg(test)]
282static AFTER_UPDATE_PRECHECK_HOOKS: std::sync::LazyLock<
283 std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, AfterUpdatePrecheckHook>>,
284> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
285
286#[cfg(test)]
287struct AfterUpdatePrecheckHookRegistration {
288 update_path: std::path::PathBuf,
289}
290
291#[cfg(test)]
292impl Drop for AfterUpdatePrecheckHookRegistration {
293 fn drop(&mut self) {
294 AFTER_UPDATE_PRECHECK_HOOKS
295 .lock()
296 .unwrap_or_else(std::sync::PoisonError::into_inner)
297 .remove(&self.update_path);
298 }
299}
300
301#[cfg(test)]
302fn install_after_update_precheck_hook(
303 update_path: std::path::PathBuf,
304 hook: AfterUpdatePrecheckHook,
305) -> AfterUpdatePrecheckHookRegistration {
306 let replaced = AFTER_UPDATE_PRECHECK_HOOKS
307 .lock()
308 .unwrap_or_else(std::sync::PoisonError::into_inner)
309 .insert(update_path.clone(), hook);
310 assert!(replaced.is_none(), "update precheck hook already installed");
311 AfterUpdatePrecheckHookRegistration { update_path }
312}
313
314#[cfg(test)]
315fn run_after_update_precheck_hook(update_path: &std::path::Path) {
316 let hook = AFTER_UPDATE_PRECHECK_HOOKS
317 .lock()
318 .unwrap_or_else(std::sync::PoisonError::into_inner)
319 .remove(update_path);
320 if let Some(hook) = hook {
321 hook();
322 }
323}
324
325async fn link_inner(
326 prog_track: &'static progress::Progress,
327 cwd: &std::path::Path,
328 src: &std::path::Path,
329 dst: &std::path::Path,
330 update: &Option<std::path::PathBuf>,
331 settings: &Settings,
332 is_fresh: bool,
333) -> Result<Summary, Error> {
334 let _ = cwd;
337 let update_root_requirement = UpdateRootRequirement::from_settings(settings);
338 let permit = walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
341 #[allow(clippy::large_enum_variant)]
343 enum LinkRootSetup {
344 Complete(Summary),
345 Ready {
346 src_operand: crate::walk::RootOperand,
347 src_parent: Arc<Dir>,
348 dst_parent: Option<Arc<Dir>>,
349 preview_parent: Option<copy::PreviewParent>,
350 update_parent: Option<(Arc<Dir>, std::ffi::OsString)>,
351 admission: LinkEntryAdmission,
352 },
353 }
354 let setup_admission = permit.as_ref().map(LeafPermit::admission);
355 let setup = safedir::with_optional_fd_admission(setup_admission, async move {
356 if let Some(update_path) = update.as_ref() {
368 if crate::safedir::strict_operand_resolution() {
369 let kind =
376 crate::safedir::strict_probe_dst_kind(update_path, congestion::Side::Source)
377 .await
378 .map_err(|err| {
379 Error::new(
380 anyhow::Error::new(err).context(format!(
381 "failed reading metadata from update {update_path:?}"
382 )),
383 Default::default(),
384 )
385 })?;
386 if update_root_requirement.is_required() && kind.is_none() {
387 return Err(missing_destructive_update_error(update_path));
388 }
389 } else if update_root_requirement.is_required() {
390 match crate::walk::run_metadata_probed(
391 congestion::Side::Source,
392 congestion::MetadataOp::Stat,
393 tokio::fs::symlink_metadata(update_path),
394 )
395 .await
396 {
397 Ok(_) => {}
398 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
399 return Err(missing_destructive_update_error(update_path));
400 }
401 Err(err) => {
402 return Err(Error::new(
403 anyhow::Error::new(err).context(format!(
404 "failed reading metadata from update {:?}",
405 update_path
406 )),
407 Default::default(),
408 ));
409 }
410 }
411 }
412 }
413 #[cfg(test)]
414 if let Some(update_path) = update.as_ref() {
415 run_after_update_precheck_hook(update_path);
416 }
417 let src_operand = crate::walk::split_root_operand(src)
421 .await
422 .map_err(|err| Error::new(err, Default::default()))?;
423 let src = src_operand.display.as_path();
424 let src_name = src_operand.name.as_os_str();
425 let strict_src_parent: Option<Arc<Dir>> = if crate::safedir::strict_operand_resolution() {
432 let parent = Dir::open_parent_dir(&src_operand.parent, congestion::Side::Source)
433 .await
434 .with_context(|| {
435 format!(
436 "cannot open source parent directory {:?}",
437 src_operand.parent
438 )
439 })
440 .map_err(|err| Error::new(err, Default::default()))?;
441 Some(Arc::new(parent.into_tree()))
443 } else {
444 None
445 };
446 let dst_parent_path_opt: Option<&std::path::Path> = match (dst.parent(), dst.file_name()) {
451 (Some(parent), Some(_)) if parent.as_os_str().is_empty() => {
452 Some(std::path::Path::new("."))
453 }
454 (Some(parent), Some(_)) => Some(parent),
455 _ => None,
456 };
457 let preview_parent =
463 if crate::safedir::strict_operand_resolution() && settings.dry_run.is_some() {
464 match dst_parent_path_opt {
465 Some(path) => Some(
466 copy::PreviewParent::open(path)
467 .await
468 .with_context(|| {
469 format!("cannot open destination parent directory {path:?}")
470 })
471 .map_err(|err| Error::new(err, Default::default()))?,
472 ),
473 None => None,
474 }
475 } else {
476 None
477 };
478 let strict_dst_parent: Option<Arc<Dir>> = match (
479 crate::safedir::strict_operand_resolution() && settings.dry_run.is_none(),
480 dst_parent_path_opt,
481 ) {
482 (true, Some(dst_parent_path)) => {
483 match Dir::open_parent_dir(dst_parent_path, congestion::Side::Destination).await {
484 Ok(parent) => Some(Arc::new(parent.into_tree())),
485 Err(err)
486 if err.kind() == std::io::ErrorKind::NotFound
487 || err.raw_os_error() == Some(libc::ENOTDIR) =>
488 {
489 None
490 }
491 Err(err) => {
492 return Err(Error::new(
493 anyhow::Error::new(err).context(format!(
494 "cannot open destination parent directory {dst_parent_path:?}"
495 )),
496 Default::default(),
497 ));
498 }
499 }
500 }
501 _ => None,
503 };
504 if strict_src_parent.is_none()
511 && let (Some(filter), Some(update_path)) = (settings.filter.as_ref(), update.as_ref())
512 {
513 let src_metadata = crate::walk::run_metadata_probed(
514 congestion::Side::Source,
515 congestion::MetadataOp::Stat,
516 tokio::fs::symlink_metadata(src),
517 )
518 .await;
519 let update_metadata = crate::walk::run_metadata_probed(
520 congestion::Side::Source,
521 congestion::MetadataOp::Stat,
522 tokio::fs::symlink_metadata(update_path),
523 )
524 .await;
525 if let (Ok(src_metadata), Ok(update_metadata)) = (src_metadata, update_metadata)
526 && let RootFilterSelection::Skip { kind, result } = select_filtered_root(
527 filter,
528 src_name,
529 EntryKind::from_metadata(&src_metadata),
530 Some(EntryKind::from_metadata(&update_metadata)),
531 settings.update_exclusive,
532 )
533 {
534 if let Some(mode) = settings.dry_run {
535 crate::dry_run::report_skip(src, &result, mode, kind.label_long());
536 }
537 kind.inc_skipped(prog_track);
538 return Ok(LinkRootSetup::Complete(skipped_summary_for(kind)));
539 }
540 }
541 if update.is_none()
545 && let Some(ref filter) = settings.filter
546 {
547 let (kind, is_dir) = match &strict_src_parent {
548 Some(parent) => {
550 let root_handle = parent
551 .child(src_name)
552 .await
553 .with_context(|| format!("failed reading metadata from {:?}", &src))
554 .map_err(|err| Error::new(err, Default::default()))?;
555 (root_handle.kind(), root_handle.kind() == EntryKind::Dir)
556 }
557 None => {
558 let src_metadata = crate::walk::run_metadata_probed(
559 congestion::Side::Source,
560 congestion::MetadataOp::Stat,
561 tokio::fs::symlink_metadata(src),
562 )
563 .await
564 .with_context(|| format!("failed reading metadata from {:?}", &src))
565 .map_err(|err| Error::new(err, Default::default()))?;
566 (
567 EntryKind::from_metadata(&src_metadata),
568 src_metadata.is_dir(),
569 )
570 }
571 };
572 let result = filter.should_include_root_item(std::path::Path::new(src_name), is_dir);
573 match result {
574 crate::filter::FilterResult::Included => {}
575 result => {
576 if let Some(mode) = settings.dry_run {
577 crate::dry_run::report_skip(src, &result, mode, kind.label_long());
578 }
579 kind.inc_skipped(prog_track);
580 return Ok(LinkRootSetup::Complete(skipped_summary_for(kind)));
581 }
582 }
583 }
584 let src_parent = match strict_src_parent {
590 Some(parent) => parent,
591 None => {
592 let parent = Dir::open_parent_dir(&src_operand.parent, congestion::Side::Source)
593 .await
594 .with_context(|| {
595 format!(
596 "cannot open source parent directory {:?}",
597 src_operand.parent
598 )
599 })
600 .map_err(|err| Error::new(err, Default::default()))?;
601 Arc::new(parent.into_tree())
603 }
604 };
605 let update_parent = match update.as_ref() {
618 Some(update_path) => {
619 let update_operand = crate::walk::split_root_operand(update_path)
625 .await
626 .map_err(|err| Error::new(err, Default::default()))?;
627 let update_parent_path = update_operand.parent;
628 let update_name = update_operand.name;
629 let fallback_eligible = !update_root_requirement.is_required();
632 match Dir::open_parent_dir(&update_parent_path, congestion::Side::Source).await {
633 Ok(dir) => Some((Arc::new(dir.into_tree()), update_name)),
635 Err(err)
636 if fallback_eligible
637 && (matches!(
638 err.kind(),
639 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
640 ) || err.raw_os_error() == Some(libc::ENOTDIR)) =>
641 {
642 tracing::debug!(
646 "update parent {:?} not found ({:#}); falling back to no-update mode",
647 update_parent_path,
648 err
649 );
650 None
651 }
652 Err(err) => {
653 return Err(Error::new(
654 anyhow::Error::new(err).context(format!(
655 "cannot open update parent directory {:?}",
656 update_parent_path
657 )),
658 Default::default(),
659 ));
660 }
661 }
662 }
663 None => None,
664 };
665 let admission = match (settings.filter.as_ref(), update.as_ref()) {
670 (Some(filter), Some(update_path)) => {
671 let src_handle = src_parent
672 .child(src_name)
673 .await
674 .with_context(|| format!("failed reading metadata from {src:?}"))
675 .map_err(|err| Error::new(err, Default::default()))?;
676 let mut entry = AdmittedLinkEntry::new(src_handle, permit);
677 entry.update_handle = match update_parent.as_ref() {
678 Some((parent, update_name)) => update_root_requirement
679 .classify(parent.child(update_name).await, update_path)?,
680 None => None,
681 };
682 if settings.update_exclusive && entry.update_handle.is_none() {
683 return Ok(LinkRootSetup::Complete(Default::default()));
684 }
685 match select_filtered_root(
686 filter,
687 src_name,
688 entry.src_handle.kind(),
689 entry.update_handle.as_ref().map(Handle::kind),
690 settings.update_exclusive,
691 ) {
692 RootFilterSelection::SourceOnly => entry.update_handle = None,
693 RootFilterSelection::WithUpdate => {}
694 RootFilterSelection::Skip { kind, result } => {
695 if let Some(mode) = settings.dry_run {
696 crate::dry_run::report_skip(src, &result, mode, kind.label_long());
697 }
698 kind.inc_skipped(prog_track);
699 return Ok(LinkRootSetup::Complete(skipped_summary_for(kind)));
700 }
701 }
702 LinkEntryAdmission::Filtered(entry)
703 }
704 _ => LinkEntryAdmission::from(EntryAdmission::from(permit)),
705 };
706 let (Some(dst_parent_path), Some(_dst_name)) = (dst.parent(), dst.file_name()) else {
710 return Err(Error::new(
711 anyhow!(
712 "link destination {:?} has no parent directory or file name",
713 dst
714 ),
715 Default::default(),
716 ));
717 };
718 let dst_parent_path = if dst_parent_path.as_os_str().is_empty() {
719 std::path::Path::new(".")
720 } else {
721 dst_parent_path
722 };
723 let root_acl_notice = crate::safedir::RootAclNotice {
736 file_acl_preserved: update.is_none() || settings.preserve.file.acl,
737 ..crate::safedir::RootAclNotice::for_preserve(&settings.preserve)
738 };
739 match &admission {
740 LinkEntryAdmission::Filtered(entry) => {
741 crate::safedir::warn_if_root_acl_unpreserved(
742 &entry.src_handle,
743 src,
744 root_acl_notice,
745 )
746 .await;
747 }
748 LinkEntryAdmission::Unclassified { .. } => {
749 crate::safedir::warn_if_root_acl_unpreserved_at(
750 &src_parent,
751 src_name,
752 src,
753 root_acl_notice,
754 )
755 .await;
756 }
757 }
758 let dst_parent = if settings.dry_run.is_some() {
764 None
765 } else {
766 match strict_dst_parent {
767 Some(parent) => Some(parent),
768 None => {
769 let dir = Dir::open_parent_dir(dst_parent_path, congestion::Side::Destination)
770 .await
771 .with_context(|| {
772 format!(
773 "cannot open destination parent directory {:?}",
774 dst_parent_path
775 )
776 })
777 .map_err(|err| Error::new(err, Default::default()))?;
778 Some(Arc::new(dir.into_tree()))
780 }
781 }
782 };
783 Ok(LinkRootSetup::Ready {
784 src_operand,
785 src_parent,
786 dst_parent,
787 preview_parent,
788 update_parent,
789 admission,
790 })
791 })
792 .await?;
793 let (src_operand, src_parent, dst_parent, preview_parent, update_parent, admission) =
794 match setup {
795 LinkRootSetup::Complete(summary) => return Ok(summary),
796 LinkRootSetup::Ready {
797 src_operand,
798 src_parent,
799 dst_parent,
800 preview_parent,
801 update_parent,
802 admission,
803 } => (
804 src_operand,
805 src_parent,
806 dst_parent,
807 preview_parent,
808 update_parent,
809 admission,
810 ),
811 };
812 let src = src_operand.display.as_path();
813 let src_name = src_operand.name.as_os_str();
814 let update_ref = update_parent
815 .as_ref()
816 .map(|(dir, name)| (dir, name.as_os_str()));
817 link_internal(
818 prog_track,
819 &src_parent,
820 update_ref,
821 dst_parent.as_ref(),
822 src_name,
823 src,
824 dst,
825 update.as_deref(),
826 std::path::Path::new(""),
827 update_root_requirement,
828 settings,
829 is_fresh,
830 admission,
831 copy::DestinationContext::for_operand(src, update.as_deref(), dst)
832 .with_preview_parent(preview_parent),
833 )
834 .await
835 .map(|result| result.summary)
836}
837struct AdmittedLinkEntry<S = Handle, U = Handle, P = LeafPermit> {
839 src_handle: S,
840 update_handle: Option<U>,
841 permit: Option<P>,
842}
843
844enum LinkEntryAdmission {
846 Unclassified {
847 admission: EntryAdmission,
848 hinted_src_handle: Option<Handle>,
849 },
850 Filtered(AdmittedLinkEntry),
851}
852
853struct LinkEntryResult {
855 summary: Summary,
856 protect_destination: bool,
857}
858
859impl LinkEntryResult {
860 fn selected(summary: Summary) -> Self {
861 Self {
862 summary,
863 protect_destination: true,
864 }
865 }
866
867 fn filtered(summary: Summary) -> Self {
868 Self {
869 summary,
870 protect_destination: false,
871 }
872 }
873}
874
875struct LinkTaskResult {
877 summary: Summary,
878 keep_name: Option<std::ffi::OsString>,
879}
880
881impl LinkTaskResult {
882 fn from_link(name: std::ffi::OsString, result: LinkEntryResult) -> Self {
883 Self {
884 summary: result.summary,
885 keep_name: result.protect_destination.then_some(name),
886 }
887 }
888
889 fn from_update(name: std::ffi::OsString, result: LinkEntryResult) -> Self {
890 Self::from_link(name, result)
891 }
892
893 fn fold(self, summary: &mut Summary, outcomes: &mut LinkChildOutcomes) {
894 if let Some(name) = self.keep_name {
895 outcomes.record_exact(name);
896 }
897 *summary = *summary + self.summary;
898 }
899}
900
901impl LinkEntryAdmission {
902 fn admission(&self) -> Option<throttle::FdAdmission> {
903 match self {
904 Self::Unclassified { admission, .. } => admission.admission(),
905 Self::Filtered(entry) => entry.permit.as_ref().map(LeafPermit::admission),
906 }
907 }
908}
909
910impl From<EntryAdmission> for LinkEntryAdmission {
911 fn from(admission: EntryAdmission) -> Self {
912 Self::Unclassified {
913 admission,
914 hinted_src_handle: None,
915 }
916 }
917}
918
919enum RootFilterSelection {
921 SourceOnly,
922 WithUpdate,
923 Skip {
924 kind: EntryKind,
925 result: crate::filter::FilterResult,
926 },
927}
928
929fn select_filtered_root(
931 filter: &crate::filter::FilterSettings,
932 logical_name: &std::ffi::OsStr,
933 src_kind: EntryKind,
934 update_kind: Option<EntryKind>,
935 update_exclusive: bool,
936) -> RootFilterSelection {
937 let logical_name = std::path::Path::new(logical_name);
938 let src_result = filter.should_include_root_item(logical_name, src_kind == EntryKind::Dir);
939 let src_included = matches!(&src_result, crate::filter::FilterResult::Included);
940 let Some(update_kind) = update_kind else {
941 return if src_included {
942 RootFilterSelection::SourceOnly
943 } else {
944 RootFilterSelection::Skip {
945 kind: src_kind,
946 result: src_result,
947 }
948 };
949 };
950 let update_result =
951 filter.should_include_root_item(logical_name, update_kind == EntryKind::Dir);
952 if matches!(&update_result, crate::filter::FilterResult::Included) {
953 RootFilterSelection::WithUpdate
954 } else if !update_exclusive && src_included {
955 RootFilterSelection::SourceOnly
956 } else {
957 let (kind, result) = if update_exclusive {
958 (update_kind, update_result)
959 } else {
960 (src_kind, src_result)
961 };
962 RootFilterSelection::Skip { kind, result }
963 }
964}
965
966fn select_filtered_nested(
968 filter: &crate::filter::FilterSettings,
969 logical_path: &std::path::Path,
970 src_kind: EntryKind,
971 update_kind: Option<EntryKind>,
972 update_exclusive: bool,
973) -> RootFilterSelection {
974 let src_result = filter.should_include(logical_path, src_kind == EntryKind::Dir);
975 let src_included = matches!(&src_result, crate::filter::FilterResult::Included);
976 let Some(update_kind) = update_kind else {
977 return if src_included {
978 RootFilterSelection::SourceOnly
979 } else {
980 RootFilterSelection::Skip {
981 kind: src_kind,
982 result: src_result,
983 }
984 };
985 };
986 let update_result = filter.should_include(logical_path, update_kind == EntryKind::Dir);
987 if matches!(&update_result, crate::filter::FilterResult::Included) {
988 RootFilterSelection::WithUpdate
989 } else if !update_exclusive && src_included {
990 RootFilterSelection::SourceOnly
991 } else {
992 let (kind, result) = if update_exclusive {
993 (update_kind, update_result)
994 } else {
995 (src_kind, src_result)
996 };
997 RootFilterSelection::Skip { kind, result }
998 }
999}
1000
1001fn drop_link_handles_before_permit<S, U, P>(
1002 src_handle: S,
1003 update_handle: Option<U>,
1004 permit: Option<P>,
1005) {
1006 drop(src_handle);
1007 drop(update_handle);
1008 drop(permit);
1009}
1010
1011impl AdmittedLinkEntry<Handle, Handle, LeafPermit> {
1012 fn new(src_handle: Handle, permit: Option<LeafPermit>) -> Self {
1013 Self {
1014 src_handle,
1015 update_handle: None,
1016 permit,
1017 }
1018 }
1019
1020 #[allow(clippy::result_large_err)]
1023 fn into_source_leaf(self) -> Result<AdmittedLeaf, Self> {
1024 let Self {
1025 src_handle,
1026 update_handle,
1027 permit,
1028 } = self;
1029 match AdmittedLeaf::try_new(src_handle, permit) {
1030 Ok(leaf) => {
1031 drop(update_handle);
1032 Ok(leaf)
1033 }
1034 Err((src_handle, permit)) => Err(Self {
1035 src_handle,
1036 update_handle,
1037 permit,
1038 }),
1039 }
1040 }
1041
1042 fn into_update_entry(self) -> AdmittedEntry {
1043 let Self {
1044 src_handle,
1045 update_handle,
1046 permit,
1047 } = self;
1048 drop(src_handle);
1049 let update_handle =
1050 update_handle.expect("update action requires a classified update entry");
1051 AdmittedEntry::new(update_handle, permit)
1052 }
1053
1054 fn into_source_entry(self) -> AdmittedEntry {
1055 let Self {
1056 src_handle,
1057 update_handle,
1058 permit,
1059 } = self;
1060 drop(update_handle);
1061 AdmittedEntry::new(src_handle, permit)
1062 }
1063
1064 fn close_for_directory(self) -> bool {
1065 let Self {
1066 src_handle,
1067 update_handle,
1068 permit,
1069 } = self;
1070 let has_update_dir = update_handle
1071 .as_ref()
1072 .is_some_and(|handle| handle.kind() == EntryKind::Dir);
1073 drop_link_handles_before_permit(src_handle, update_handle, permit);
1074 has_update_dir
1075 }
1076}
1077
1078#[instrument(skip(prog_track, src_parent, update, dst_parent, settings, admission))]
1093#[async_recursion]
1094#[allow(clippy::too_many_arguments)]
1095async fn link_internal(
1096 prog_track: &'static progress::Progress,
1097 src_parent: &Arc<Dir>,
1098 update: Option<(&Arc<Dir>, &std::ffi::OsStr)>,
1099 dst_parent: Option<&Arc<Dir>>,
1100 name: &std::ffi::OsStr,
1101 src_root: &std::path::Path,
1102 dst_root: &std::path::Path,
1103 update_root: Option<&std::path::Path>,
1104 rel_path: &std::path::Path,
1105 update_root_requirement: UpdateRootRequirement,
1106 settings: &Settings,
1107 is_fresh: bool,
1108 admission: LinkEntryAdmission,
1109 mut destination: copy::DestinationContext,
1110) -> Result<LinkEntryResult, Error> {
1111 let _prog_guard = prog_track.ops.guard();
1112 let src_path = walk::join_rel(src_root, rel_path);
1114 let dst_path = walk::join_rel(dst_root, rel_path);
1115 let update_path = update_root.map(|root| walk::join_rel(root, rel_path));
1116 let dst_name = if rel_path.as_os_str().is_empty() {
1118 dst_root.file_name().ok_or_else(|| {
1119 Error::new(
1120 anyhow!("link destination {:?} has no file name", &dst_path),
1121 Default::default(),
1122 )
1123 })?
1124 } else {
1125 name
1126 };
1127 let mut admission = admission;
1128 if let LinkEntryAdmission::Unclassified {
1129 admission: entry_admission,
1130 hinted_src_handle,
1131 } = &mut admission
1132 {
1133 let current = std::mem::replace(entry_admission, EntryAdmission::RootOrDelegated);
1134 *entry_admission = if update.is_some() {
1135 current.require_admission()
1136 } else {
1137 current
1138 };
1139 if matches!(entry_admission, EntryAdmission::HintedDirectory) {
1143 tracing::debug!("classifying hinted source entry");
1144 let handle = walk::classify_entry(src_parent, name)
1145 .await
1146 .with_context(|| format!("failed reading metadata from {:?}", &src_path))
1147 .map_err(|err| Error::new(err, Default::default()))?;
1148 if handle.kind() == EntryKind::Dir {
1149 *hinted_src_handle = Some(handle);
1150 } else {
1151 drop(handle);
1152 *entry_admission = EntryAdmission::RootOrDelegated;
1153 }
1154 }
1155 if hinted_src_handle.is_none() || update.is_some() {
1156 let current = std::mem::replace(entry_admission, EntryAdmission::RootOrDelegated);
1157 *entry_admission = walk::ensure_entry_admission(PermitKind::OpenFile, current).await;
1158 }
1159 }
1160 let weak_admission = admission.admission();
1161
1162 enum LinkDispatch {
1163 Complete(LinkEntryResult),
1164 Directory { has_update_dir: bool },
1165 }
1166
1167 let dispatch = safedir::with_optional_fd_admission(weak_admission, async {
1168 let (mut entry, root_filter_applied) = match admission {
1169 LinkEntryAdmission::Filtered(entry) => (entry, true),
1170 LinkEntryAdmission::Unclassified {
1171 admission,
1172 hinted_src_handle,
1173 } => {
1174 let src_handle = match hinted_src_handle {
1175 Some(handle) => handle,
1176 None => {
1177 tracing::debug!("classifying source entry");
1178 walk::classify_entry(src_parent, name)
1179 .await
1180 .with_context(|| {
1181 format!("failed reading metadata from {:?}", &src_path)
1182 })
1183 .map_err(|err| Error::new(err, Default::default()))?
1184 }
1185 };
1186 let mut entry = AdmittedLinkEntry::new(src_handle, admission.into_permit());
1187 entry.update_handle = match update {
1191 Some((update_dir, update_name)) => {
1192 tracing::debug!("classifying 'update' entry");
1193 let update_path = update_path
1194 .as_deref()
1195 .expect("update directory present implies update path present");
1196 update_root_requirement
1197 .for_entry(rel_path)
1198 .classify(update_dir.child(update_name).await, update_path)?
1199 }
1200 None => None,
1201 };
1202 if update.is_some() && settings.update_exclusive && entry.update_handle.is_none() {
1203 return Ok(LinkDispatch::Complete(LinkEntryResult::filtered(
1204 Default::default(),
1205 )));
1206 }
1207 (entry, false)
1208 }
1209 };
1210 if !root_filter_applied
1214 && rel_path.as_os_str().is_empty()
1215 && let Some(filter) = settings.filter.as_ref()
1216 {
1217 match select_filtered_root(
1218 filter,
1219 name,
1220 entry.src_handle.kind(),
1221 entry.update_handle.as_ref().map(Handle::kind),
1222 settings.update_exclusive,
1223 ) {
1224 RootFilterSelection::SourceOnly => entry.update_handle = None,
1225 RootFilterSelection::WithUpdate => {}
1226 RootFilterSelection::Skip { kind, result } => {
1227 if let Some(mode) = settings.dry_run {
1228 crate::dry_run::report_skip(&src_path, &result, mode, kind.label_long());
1229 }
1230 kind.inc_skipped(prog_track);
1231 return Ok(LinkDispatch::Complete(LinkEntryResult::filtered(
1232 skipped_summary_for(kind),
1233 )));
1234 }
1235 }
1236 } else if !rel_path.as_os_str().is_empty()
1240 && let Some(filter) = settings.filter.as_ref()
1241 {
1242 match select_filtered_nested(
1243 filter,
1244 rel_path,
1245 entry.src_handle.kind(),
1246 entry.update_handle.as_ref().map(Handle::kind),
1247 settings.update_exclusive,
1248 ) {
1249 RootFilterSelection::SourceOnly => entry.update_handle = None,
1250 RootFilterSelection::WithUpdate => {}
1251 RootFilterSelection::Skip { kind, result } => {
1252 if let Some(mode) = settings.dry_run {
1253 crate::dry_run::report_skip(&src_path, &result, mode, kind.label_long());
1254 }
1255 kind.inc_skipped(prog_track);
1256 return Ok(LinkDispatch::Complete(LinkEntryResult::filtered(
1257 skipped_summary_for(kind),
1258 )));
1259 }
1260 }
1261 }
1262 if rel_path.as_os_str().is_empty()
1263 && (settings.copy_settings.overwrite || settings.copy_settings.delete.is_some())
1264 {
1265 destination
1266 .record_root(src_parent, name, &entry.src_handle, &src_path)
1267 .await
1268 .map_err(|error| Error::new(error.into(), Default::default()))?;
1269 let mut directories = Vec::with_capacity(2);
1270 if entry.src_handle.kind() == EntryKind::Dir {
1271 directories.push(entry.src_handle.meta());
1272 }
1273 if let (Some((parent, name)), Some(handle), Some(path)) =
1274 (update, entry.update_handle.as_ref(), update_path.as_deref())
1275 {
1276 destination
1277 .record_root(parent, name, handle, path)
1278 .await
1279 .map_err(|error| Error::new(error.into(), Default::default()))?;
1280 if handle.kind() == EntryKind::Dir {
1281 directories.push(handle.meta());
1282 }
1283 }
1284 destination
1285 .reserve_roots(&directories)
1286 .map_err(|error| Error::new(error.into(), Default::default()))?;
1287 }
1288 if let Some(update_entry) = entry.update_handle.as_ref() {
1295 let (update_dir, update_name) = update.unwrap();
1296 let update_path = update_path.as_deref().unwrap();
1297 if update_entry.kind() != entry.src_handle.kind() {
1298 tracing::debug!(
1300 "link: file type of {:?} ({:?}) and {:?} ({:?}) differs - copying from update",
1301 src_path,
1302 entry.src_handle.kind(),
1303 update_path,
1304 update_entry.kind()
1305 );
1306 let admission = entry.into_update_entry();
1312 return delegate_copy(
1313 prog_track,
1314 update_dir,
1315 dst_parent,
1316 update_name,
1317 update_path,
1318 dst_root,
1319 rel_path,
1320 destination.clone(),
1321 settings,
1322 is_fresh,
1323 admission,
1324 )
1325 .await
1326 .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1327 }
1328 if update_entry.kind() == EntryKind::File {
1329 if filecmp::metadata_equal(
1331 &settings.update_compare,
1332 entry.src_handle.meta(),
1333 update_entry.meta(),
1334 ) {
1335 tracing::debug!("no change, hard link 'src'");
1337 let leaf = match entry.into_source_leaf() {
1338 Ok(leaf) => leaf,
1339 Err(entry) => {
1340 return Ok(LinkDispatch::Directory {
1341 has_update_dir: entry.close_for_directory(),
1342 });
1343 }
1344 };
1345 if settings.dry_run.is_some() {
1346 crate::dry_run::report_action("link", &src_path, Some(&dst_path), "file");
1347 return Ok(LinkDispatch::Complete(LinkEntryResult::selected(Summary {
1348 hard_links_created: 1,
1349 ..Default::default()
1350 })));
1351 }
1352 let dst_dir =
1353 dst_parent.expect("destination parent must be open for a real hard link");
1354 return hard_link_entry_fd(
1355 prog_track,
1356 leaf.handle(),
1357 dst_dir,
1358 dst_name,
1359 &dst_path,
1360 settings,
1361 &destination,
1362 )
1363 .await
1364 .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1365 }
1366 tracing::debug!(
1367 "link: {:?} metadata has changed, copying from {:?}",
1368 src_path,
1369 update_path
1370 );
1371 let admission = entry.into_update_entry();
1373 return delegate_copy(
1374 prog_track,
1375 update_dir,
1376 dst_parent,
1377 update_name,
1378 update_path,
1379 dst_root,
1380 rel_path,
1381 destination.clone(),
1382 settings,
1383 is_fresh,
1384 admission,
1385 )
1386 .await
1387 .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1388 }
1389 if update_entry.kind() == EntryKind::Symlink {
1390 tracing::debug!("'update' is a symlink so just symlink that");
1393 let admission = entry.into_update_entry();
1394 return delegate_copy(
1395 prog_track,
1396 update_dir,
1397 dst_parent,
1398 update_name,
1399 update_path,
1400 dst_root,
1401 rel_path,
1402 destination.clone(),
1403 settings,
1404 is_fresh,
1405 admission,
1406 )
1407 .await
1408 .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1409 }
1410 } else {
1411 tracing::debug!("no 'update' entry");
1414 if entry.src_handle.kind() == EntryKind::File {
1415 let leaf = match entry.into_source_leaf() {
1416 Ok(leaf) => leaf,
1417 Err(entry) => {
1418 return Ok(LinkDispatch::Directory {
1419 has_update_dir: entry.close_for_directory(),
1420 });
1421 }
1422 };
1423 if settings.dry_run.is_some() {
1424 crate::dry_run::report_action("link", &src_path, Some(&dst_path), "file");
1425 return Ok(LinkDispatch::Complete(LinkEntryResult::selected(Summary {
1426 hard_links_created: 1,
1427 ..Default::default()
1428 })));
1429 }
1430 let dst_dir =
1431 dst_parent.expect("destination parent must be open for a real hard link");
1432 return hard_link_entry_fd(
1433 prog_track,
1434 leaf.handle(),
1435 dst_dir,
1436 dst_name,
1437 &dst_path,
1438 settings,
1439 &destination,
1440 )
1441 .await
1442 .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1443 }
1444 if entry.src_handle.kind() == EntryKind::Symlink {
1445 tracing::debug!("'src' is a symlink so just symlink that");
1446 let admission = entry.into_source_entry();
1447 return delegate_copy(
1448 prog_track,
1449 src_parent,
1450 dst_parent,
1451 name,
1452 &src_path,
1453 dst_root,
1454 rel_path,
1455 destination.clone(),
1456 settings,
1457 is_fresh,
1458 admission,
1459 )
1460 .await
1461 .map(|summary| LinkDispatch::Complete(LinkEntryResult::selected(summary)));
1462 }
1463 }
1464 if entry.src_handle.kind() != EntryKind::Dir {
1465 if settings.copy_settings.skip_specials {
1468 tracing::debug!(
1469 "skipping special file {:?} (kind: {:?})",
1470 src_path,
1471 entry.src_handle.kind()
1472 );
1473 if let Some(mode) = settings.dry_run {
1474 match mode {
1475 crate::config::DryRunMode::Brief => {}
1476 crate::config::DryRunMode::All => println!("skip special {:?}", src_path),
1477 crate::config::DryRunMode::Explain => {
1478 println!(
1479 "skip special {:?} (unsupported file type: {:?})",
1480 src_path,
1481 entry.src_handle.kind()
1482 );
1483 }
1484 }
1485 }
1486 prog_track.specials_skipped.inc();
1487 return Ok(LinkDispatch::Complete(LinkEntryResult::selected(Summary {
1488 copy_summary: CopySummary {
1489 specials_skipped: 1,
1490 ..Default::default()
1491 },
1492 ..Default::default()
1493 })));
1494 }
1495 return Err(Error::new(
1496 anyhow!(
1497 "copy: {:?} -> {:?} failed, unsupported src file type: {:?}",
1498 src_path,
1499 dst_path,
1500 entry.src_handle.kind()
1501 ),
1502 Default::default(),
1503 ));
1504 }
1505 debug_assert!(
1508 entry.update_handle.is_none()
1509 || entry.update_handle.as_ref().unwrap().kind() == EntryKind::Dir
1510 );
1511 let has_update_dir = entry.close_for_directory();
1517 Ok(LinkDispatch::Directory { has_update_dir })
1518 })
1519 .await?;
1520 let has_update_dir = match dispatch {
1521 LinkDispatch::Complete(summary) => return Ok(summary),
1522 LinkDispatch::Directory { has_update_dir } => has_update_dir,
1523 };
1524 let update_for_dir = update.filter(|_| has_update_dir);
1525 let update_root_for_dir = update_root.filter(|_| has_update_dir);
1526 let update_path_for_dir = update_path.as_deref().filter(|_| has_update_dir);
1527 link_dir_entry(
1528 prog_track,
1529 src_parent,
1530 update_for_dir,
1531 dst_parent,
1532 name,
1533 dst_name,
1534 src_root,
1535 dst_root,
1536 update_root_for_dir,
1537 rel_path,
1538 &src_path,
1539 &dst_path,
1540 update_path_for_dir,
1541 settings,
1542 is_fresh,
1543 destination,
1544 )
1545 .await
1546 .map(LinkEntryResult::selected)
1547}
1548
1549#[allow(clippy::too_many_arguments)]
1557async fn delegate_copy(
1558 prog_track: &'static progress::Progress,
1559 src_parent: &Arc<Dir>,
1560 dst_parent: Option<&Arc<Dir>>,
1561 name: &std::ffi::OsStr,
1562 src_path: &std::path::Path,
1563 dst_root: &std::path::Path,
1564 filter_base: &std::path::Path,
1565 destination: copy::DestinationContext,
1566 settings: &Settings,
1567 is_fresh: bool,
1568 admission: AdmittedEntry,
1569) -> Result<Summary, Error> {
1570 let normalized_copy_settings =
1574 (settings.copy_settings.dry_run != settings.dry_run).then(|| {
1575 let mut copy_settings = settings.copy_settings.clone();
1576 copy_settings.dry_run = settings.dry_run;
1577 copy_settings
1578 });
1579 let copy_settings = normalized_copy_settings
1580 .as_ref()
1581 .unwrap_or(&settings.copy_settings);
1582 let copy_summary = copy::copy_child(
1583 prog_track,
1584 src_parent,
1585 dst_parent,
1586 name,
1587 src_path,
1588 dst_root,
1589 filter_base,
1590 copy_settings,
1591 &settings.preserve,
1592 is_fresh,
1593 destination,
1594 admission,
1595 )
1596 .await
1597 .map_err(|err| {
1598 let copy_summary = err.summary;
1599 Error::new(
1600 err.source,
1601 Summary {
1602 copy_summary,
1603 ..Default::default()
1604 },
1605 )
1606 })?;
1607 Ok(Summary {
1608 copy_summary,
1609 ..Default::default()
1610 })
1611}
1612
1613#[allow(clippy::too_many_arguments)]
1617async fn link_dir_entry(
1618 prog_track: &'static progress::Progress,
1619 src_parent: &Arc<Dir>,
1620 update: Option<(&Arc<Dir>, &std::ffi::OsStr)>,
1621 dst_parent: Option<&Arc<Dir>>,
1622 name: &std::ffi::OsStr,
1623 dst_name: &std::ffi::OsStr,
1624 src_root: &std::path::Path,
1625 dst_root: &std::path::Path,
1626 update_root: Option<&std::path::Path>,
1627 rel_path: &std::path::Path,
1628 src_path: &std::path::Path,
1629 dst_path: &std::path::Path,
1630 update_path: Option<&std::path::Path>,
1631 settings: &Settings,
1632 is_fresh: bool,
1633 destination: copy::DestinationContext,
1634) -> Result<Summary, Error> {
1635 let (src_dir, src_meta) = src_parent
1636 .open_dir_with_meta(name)
1637 .await
1638 .with_context(|| format!("cannot open directory {:?} for reading", src_path))
1639 .map_err(|err| Error::new(err, Default::default()))?;
1640 let src_dir = Arc::new(src_dir);
1641 let (update_dir, update_meta) = match update {
1643 Some((update_parent, update_name)) => {
1644 let update_path = update_path.expect("an update directory has a display path");
1645 let (dir, meta) = update_parent
1646 .open_dir_with_meta(update_name)
1647 .await
1648 .with_context(|| {
1649 format!("cannot open update directory {:?} for reading", update_path)
1650 })
1651 .map_err(|err| Error::new(err, Default::default()))?;
1652 (Some(Arc::new(dir)), Some((meta, update_path)))
1653 }
1654 None => (None, None),
1655 };
1656 let (meta_dir, meta, meta_path) = match &update_meta {
1657 Some((meta, path)) => (
1658 update_dir.as_ref().expect("update directory is open"),
1659 meta,
1660 *path,
1661 ),
1662 None => (&src_dir, &src_meta, src_path),
1663 };
1664 let inputs = [&src_meta, meta];
1665 let inputs = &inputs[..if update_dir.is_some() { 2 } else { 1 }];
1666 let admission = destination
1667 .enter(
1668 prog_track,
1669 inputs,
1670 copy::destination::PreservationSource {
1671 dir: meta_dir,
1672 meta,
1673 path: meta_path,
1674 acl: settings.preserve.dir.acl,
1675 },
1676 dst_parent,
1677 dst_name,
1678 dst_path,
1679 &settings.copy_settings,
1680 settings.dry_run,
1681 )
1682 .await
1683 .map_err(|error| {
1684 Error::new(
1685 error.source.context(format!(
1686 "cannot link directory {src_path:?} to {dst_path:?}"
1687 )),
1688 Summary {
1689 copy_summary: error.summary,
1690 ..Default::default()
1691 },
1692 )
1693 })?;
1694 let copy::destination::Admission::Entered {
1695 destination,
1696 slot,
1697 preview,
1698 snapshot,
1699 } = admission
1700 else {
1701 let copy::destination::Admission::Skip(copy_summary) = admission else {
1702 unreachable!()
1703 };
1704 return Ok(Summary {
1705 copy_summary,
1706 ..Default::default()
1707 });
1708 };
1709 let (dst_dir, base, child_is_fresh, we_created, reused_lock) = match slot {
1710 Some(slot) => (
1711 Some(slot.dir),
1712 slot.summary,
1713 slot.is_fresh,
1714 slot.we_created,
1715 slot.reused_lock,
1716 ),
1717 None => {
1718 crate::dry_run::report_action("link", src_path, Some(dst_path), "dir");
1719 (
1720 None,
1721 CopySummary {
1722 directories_created: 1,
1723 ..Default::default()
1724 },
1725 is_fresh,
1726 true,
1727 None,
1728 )
1729 }
1730 };
1731 link_dir_contents_prepared(
1732 prog_track,
1733 &src_dir,
1734 snapshot,
1735 update_dir.as_ref(),
1736 dst_dir.as_ref(),
1737 dst_parent,
1738 dst_name,
1739 src_root,
1740 dst_root,
1741 update_root,
1742 rel_path,
1743 src_path,
1744 dst_path,
1745 we_created,
1746 child_is_fresh,
1747 reused_lock,
1748 settings,
1749 Summary {
1750 copy_summary: base,
1751 ..Default::default()
1752 },
1753 SourceEntries::Live,
1754 UpdateEntries::Live,
1755 preview.as_ref(),
1756 destination,
1757 )
1758 .await
1759}
1760
1761fn source_entry_admission(hint: Option<EntryKind>, has_update: bool) -> EntryAdmission {
1766 let admission = EntryAdmission::from_hint(hint);
1767 if has_update {
1768 admission.require_admission()
1771 } else {
1772 admission
1773 }
1774}
1775
1776fn requires_exact_entry_outcome(settings: &Settings) -> bool {
1778 settings.copy_settings.delete.is_some() || settings.dry_run.is_some()
1779}
1780
1781enum SourceEntryDecision {
1783 Filtered { kind: EntryKind },
1785 Dispatch(EntryAdmission),
1787}
1788
1789fn select_source_for_dispatch(
1793 hint: Option<EntryKind>,
1794 relative_path: &std::path::Path,
1795 settings: &Settings,
1796 has_update: bool,
1797) -> SourceEntryDecision {
1798 if !requires_exact_entry_outcome(settings)
1799 && let Some(kind) = hint
1800 && walk::should_skip_entry_ref(
1801 settings.filter.as_ref(),
1802 relative_path,
1803 kind == EntryKind::Dir,
1804 )
1805 .is_some()
1806 {
1807 return SourceEntryDecision::Filtered { kind };
1808 }
1809 SourceEntryDecision::Dispatch(source_entry_admission(hint, has_update))
1810}
1811
1812enum UpdateOnlyDecision {
1814 Skipped {
1816 kind: EntryKind,
1817 result: crate::filter::FilterResult,
1818 },
1819 Admitted(AdmittedEntry),
1821}
1822
1823fn select_exact_update_only_entry(
1824 entry: AdmittedEntry,
1825 relative_path: &std::path::Path,
1826 filter: Option<&crate::filter::FilterSettings>,
1827) -> UpdateOnlyDecision {
1828 let kind = entry.kind();
1829 match walk::should_skip_entry_ref(filter, relative_path, kind == EntryKind::Dir) {
1830 Some(result) => UpdateOnlyDecision::Skipped { kind, result },
1831 None => UpdateOnlyDecision::Admitted(entry),
1832 }
1833}
1834
1835enum UpdateOnlyDispatch {
1837 Skipped { kind: EntryKind },
1839 Dispatch(EntryAdmission),
1841}
1842
1843fn select_update_only_for_dispatch(
1845 hint: Option<EntryKind>,
1846 relative_path: &std::path::Path,
1847 settings: &Settings,
1848) -> UpdateOnlyDispatch {
1849 if !requires_exact_entry_outcome(settings)
1850 && let Some(kind) = hint
1851 && walk::should_skip_entry_ref(
1852 settings.filter.as_ref(),
1853 relative_path,
1854 kind == EntryKind::Dir,
1855 )
1856 .is_some()
1857 {
1858 return UpdateOnlyDispatch::Skipped { kind };
1859 }
1860 UpdateOnlyDispatch::Dispatch(EntryAdmission::from_hint(hint))
1861}
1862
1863async fn select_exact_update_only_for_dispatch(
1868 update_dir: &Arc<Dir>,
1869 name: &std::ffi::OsStr,
1870 mut admission: EntryAdmission,
1871 relative_path: &std::path::Path,
1872 filter: Option<&crate::filter::FilterSettings>,
1873) -> std::io::Result<UpdateOnlyDecision> {
1874 let entry = if matches!(admission, EntryAdmission::HintedDirectory) {
1875 let handle = walk::classify_entry(update_dir, name).await?;
1876 if handle.kind() == EntryKind::Dir {
1877 AdmittedEntry::new(handle, None)
1878 } else {
1879 drop(handle);
1880 admission = EntryAdmission::RootOrDelegated;
1881 let admission = walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
1882 walk::classify_admitted_entry(update_dir, name, admission.into_permit()).await?
1883 }
1884 } else {
1885 let admission = walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
1886 walk::classify_admitted_entry(update_dir, name, admission.into_permit()).await?
1887 };
1888 Ok(select_exact_update_only_entry(entry, relative_path, filter))
1889}
1890
1891#[allow(clippy::too_many_arguments)]
1894async fn process_update_only_entry(
1895 prog_track: &'static progress::Progress,
1896 update_parent: Arc<Dir>,
1897 dst_parent: Option<Arc<Dir>>,
1898 entry_name: std::ffi::OsString,
1899 update_entry_path: std::path::PathBuf,
1900 dst_root: std::path::PathBuf,
1901 entry_rel: std::path::PathBuf,
1902 destination: copy::DestinationContext,
1903 settings: Settings,
1904 is_fresh: bool,
1905 admission: EntryAdmission,
1906) -> Result<LinkTaskResult, Error> {
1907 let decision = select_exact_update_only_for_dispatch(
1908 &update_parent,
1909 &entry_name,
1910 admission,
1911 &entry_rel,
1912 settings.filter.as_ref(),
1913 )
1914 .await
1915 .with_context(|| format!("failed reading metadata from {update_entry_path:?}"))
1916 .map_err(|err| Error::new(err, Default::default()))?;
1917 let entry = match decision {
1918 UpdateOnlyDecision::Skipped { kind, result } => {
1919 if let Some(mode) = settings.dry_run {
1920 crate::dry_run::report_skip(&update_entry_path, &result, mode, kind.label());
1921 }
1922 tracing::debug!(
1923 "skipping update entry {:?} due to filter",
1924 &update_entry_path
1925 );
1926 kind.inc_skipped(prog_track);
1927 return Ok(LinkTaskResult::from_update(
1928 entry_name,
1929 LinkEntryResult::filtered(skipped_summary_for(kind)),
1930 ));
1931 }
1932 UpdateOnlyDecision::Admitted(entry) => entry,
1933 };
1934 let entry_kind = entry.kind();
1935 if settings.copy_settings.skip_specials && entry_kind == EntryKind::Special {
1936 tracing::debug!("skipping special file {:?}", &update_entry_path);
1937 if let Some(mode) = settings.dry_run {
1938 match mode {
1939 crate::config::DryRunMode::Brief => {}
1940 crate::config::DryRunMode::All => println!("skip special {:?}", &update_entry_path),
1941 crate::config::DryRunMode::Explain => {
1942 println!(
1943 "skip special {:?} (unsupported file type: {:?})",
1944 &update_entry_path, entry_kind
1945 );
1946 }
1947 }
1948 }
1949 prog_track.specials_skipped.inc();
1950 return Ok(LinkTaskResult::from_update(
1951 entry_name,
1952 LinkEntryResult::selected(Summary {
1953 copy_summary: CopySummary {
1954 specials_skipped: 1,
1955 ..Default::default()
1956 },
1957 ..Default::default()
1958 }),
1959 ));
1960 }
1961 tracing::debug!("found a new entry in the 'update' directory");
1962 let summary = delegate_copy(
1963 prog_track,
1964 &update_parent,
1965 dst_parent.as_ref(),
1966 &entry_name,
1967 &update_entry_path,
1968 &dst_root,
1969 &entry_rel,
1970 destination,
1971 &settings,
1972 is_fresh,
1973 entry,
1974 )
1975 .await?;
1976 Ok(LinkTaskResult::from_update(
1977 entry_name,
1978 LinkEntryResult::selected(summary),
1979 ))
1980}
1981
1982fn fold_link_task_result(
1983 result: Result<Result<LinkTaskResult, Error>, tokio::task::JoinError>,
1984 link_summary: &mut Summary,
1985 outcomes: &mut LinkChildOutcomes,
1986 fail_early: bool,
1987 src_path: &std::path::Path,
1988 dst_path: &std::path::Path,
1989) -> Result<(), anyhow::Error> {
1990 match result {
1991 Ok(Ok(result)) => result.fold(link_summary, outcomes),
1992 Ok(Err(error)) => {
1993 tracing::error!(
1994 "link: {:?} -> {:?} failed with: {:#}",
1995 src_path,
1996 dst_path,
1997 &error
1998 );
1999 *link_summary = *link_summary + error.summary;
2000 if fail_early {
2001 return Err(error.source);
2002 }
2003 outcomes.record_error(error.source);
2004 }
2005 Err(join_error) => {
2006 if fail_early {
2007 return Err(join_error.into());
2008 }
2009 outcomes.record_error(join_error.into());
2010 }
2011 }
2012 Ok(())
2013}
2014
2015async fn ensure_link_admission(
2019 admission: EntryAdmission,
2020 join_set: &mut tokio::task::JoinSet<Result<LinkTaskResult, Error>>,
2021 link_summary: &mut Summary,
2022 outcomes: &mut LinkChildOutcomes,
2023 fail_early: bool,
2024 src_path: &std::path::Path,
2025 dst_path: &std::path::Path,
2026) -> Result<EntryAdmission, anyhow::Error> {
2027 let admission = walk::ensure_entry_admission(PermitKind::OpenFile, admission);
2028 tokio::pin!(admission);
2029 loop {
2030 let has_tasks = !join_set.is_empty();
2031 tokio::select! {
2032 biased;
2033 result = join_set.join_next(), if has_tasks => {
2034 fold_link_task_result(
2035 result.expect("a non-empty link JoinSet must yield one task result"),
2036 link_summary,
2037 outcomes,
2038 fail_early,
2039 src_path,
2040 dst_path,
2041 )?;
2042 }
2043 admission = &mut admission => return Ok(admission),
2044 }
2045 }
2046}
2047
2048enum SourceEntries {
2049 Live,
2050 #[cfg(test)]
2051 InjectedReadError(std::io::Error),
2052 #[cfg(test)]
2053 Injected(Vec<(std::ffi::OsString, Option<EntryKind>)>),
2054}
2055
2056enum UpdateEntries {
2057 Live,
2058 #[cfg(test)]
2059 InjectedReadError(tokio::sync::oneshot::Receiver<std::io::Error>),
2060 #[cfg(test)]
2061 Injected(Vec<(std::ffi::OsString, Option<EntryKind>)>),
2062}
2063
2064#[allow(clippy::too_many_arguments)]
2073async fn link_dir_contents_prepared(
2074 prog_track: &'static progress::Progress,
2075 src_dir: &Arc<Dir>,
2076 snapshot: copy::SourceSnapshot,
2077 update_dir: Option<&Arc<Dir>>,
2078 dst_dir: Option<&Arc<Dir>>,
2079 dst_parent: Option<&Arc<Dir>>,
2080 dst_name: &std::ffi::OsStr,
2081 src_root: &std::path::Path,
2082 dst_root: &std::path::Path,
2083 update_root: Option<&std::path::Path>,
2084 rel_path: &std::path::Path,
2085 src_path: &std::path::Path,
2086 dst_path: &std::path::Path,
2087 we_created_this_dir: bool,
2088 is_fresh: bool,
2089 reused_lock: Option<crate::safedir::ReusedDirLock>,
2090 settings: &Settings,
2091 base: Summary,
2092 source_entries: SourceEntries,
2093 update_entries: UpdateEntries,
2094 preview_dir: Option<&Arc<Dir>>,
2095 destination: copy::PreparedDestination,
2096) -> Result<Summary, Error> {
2097 tracing::debug!("process contents of 'src' directory");
2098 let mut link_summary = base;
2099 let mut join_set = tokio::task::JoinSet::new();
2100 let mut processed_files = std::collections::HashSet::new();
2103 let mut outcomes = LinkChildOutcomes::new(settings.copy_settings.delete.as_ref());
2105 let enumeration_result = async {
2108 let src_entries = match source_entries {
2109 SourceEntries::Live => src_dir.read_entries().await,
2110 #[cfg(test)]
2111 SourceEntries::Injected(entries) => Ok(entries),
2112 #[cfg(test)]
2113 SourceEntries::InjectedReadError(error) => Err(error),
2114 }
2115 .with_context(|| format!("cannot open directory {src_path:?} for reading"))?;
2116 for (entry_name, hint) in src_entries {
2118 let entry_rel = walk::join_path(rel_path, std::path::Path::new(&entry_name));
2119 let decision =
2120 select_source_for_dispatch(hint, &entry_rel, settings, update_dir.is_some());
2121 let admission = match decision {
2122 SourceEntryDecision::Filtered { kind } => {
2123 tracing::debug!(
2124 "skipping {:?} due to filter",
2125 walk::join_path(src_path, std::path::Path::new(&entry_name))
2126 );
2127 link_summary = link_summary + skipped_summary_for(kind);
2128 kind.inc_skipped(prog_track);
2129 continue;
2130 }
2131 SourceEntryDecision::Dispatch(admission) => admission,
2132 };
2133 if update_dir.is_some() {
2134 processed_files.insert(entry_name.clone());
2135 }
2136 let admission = ensure_link_admission(
2137 admission,
2138 &mut join_set,
2139 &mut link_summary,
2140 &mut outcomes,
2141 settings.copy_settings.fail_early,
2142 src_path,
2143 dst_path,
2144 )
2145 .await?;
2146 let src_parent = Arc::clone(src_dir);
2152 let dst_parent = dst_dir.map(Arc::clone);
2153 let update_parent = update_dir.map(Arc::clone);
2154 let settings = settings.clone();
2155 let src_root = src_root.to_owned();
2156 let dst_root = dst_root.to_owned();
2157 let update_root = update_root.map(std::path::Path::to_path_buf);
2158 let destination = destination.child();
2159 let do_link = move || async move {
2160 let update_ref = update_parent
2161 .as_ref()
2162 .map(|dir| (dir, entry_name.as_os_str()));
2163 link_internal(
2164 prog_track,
2165 &src_parent,
2166 update_ref,
2167 dst_parent.as_ref(),
2168 &entry_name,
2169 &src_root,
2170 &dst_root,
2171 update_root.as_deref(),
2172 &entry_rel,
2173 UpdateRootRequirement::Optional,
2174 &settings,
2175 is_fresh,
2176 admission.into(),
2177 destination,
2178 )
2179 .await
2180 .map(|result| LinkTaskResult::from_link(entry_name, result))
2181 };
2182 crate::task_scope::spawn_tracked(&mut join_set, do_link());
2183 }
2184 if let Some(update_dir) = update_dir {
2186 let update_root = update_root.expect("update_dir present implies update_root present");
2187 tracing::debug!("process contents of 'update' directory");
2188 let update_entries = match update_entries {
2189 UpdateEntries::Live => update_dir.read_entries().await,
2190 #[cfg(test)]
2191 UpdateEntries::Injected(entries) => Ok(entries),
2192 #[cfg(test)]
2193 UpdateEntries::InjectedReadError(error) => {
2194 Err(error.await.expect("injected read error"))
2195 }
2196 }
2197 .with_context(|| {
2198 format!(
2199 "cannot open directory {:?} for reading",
2200 walk::join_rel(update_root, rel_path)
2201 )
2202 })?;
2203 for (entry_name, hint) in update_entries {
2208 if processed_files.contains(&entry_name) {
2209 continue;
2212 }
2213 let entry_rel = walk::join_path(rel_path, std::path::Path::new(&entry_name));
2214 let admission = match select_update_only_for_dispatch(hint, &entry_rel, settings) {
2215 UpdateOnlyDispatch::Skipped { kind } => {
2216 tracing::debug!(
2217 "skipping update entry {:?} due to filter",
2218 walk::join_rel(update_root, &entry_rel)
2219 );
2220 link_summary = link_summary + skipped_summary_for(kind);
2221 kind.inc_skipped(prog_track);
2222 continue;
2223 }
2224 UpdateOnlyDispatch::Dispatch(admission) => admission,
2225 };
2226 let update_entry_path = walk::join_rel(update_root, &entry_rel);
2227 let admission = ensure_link_admission(
2228 admission,
2229 &mut join_set,
2230 &mut link_summary,
2231 &mut outcomes,
2232 settings.copy_settings.fail_early,
2233 src_path,
2234 dst_path,
2235 )
2236 .await?;
2237 let dst_root = dst_root.to_path_buf();
2241 let update_parent = Arc::clone(update_dir);
2242 let dst_parent = dst_dir.map(Arc::clone);
2243 let settings = settings.clone();
2244 let destination = destination.child();
2245 let source_for_delete = (settings.copy_settings.delete.is_some()
2246 && !settings.update_exclusive)
2247 .then(|| {
2248 (
2249 Arc::clone(src_dir),
2250 src_root.to_owned(),
2251 update_root.to_owned(),
2252 )
2253 });
2254 let do_copy = move || async move {
2255 if let Some((src_parent, src_root, update_root)) = source_for_delete {
2256 match src_parent.child_kind(&entry_name).await {
2260 Ok(_) => {
2261 return link_internal(
2262 prog_track,
2263 &src_parent,
2264 Some((&update_parent, entry_name.as_os_str())),
2265 dst_parent.as_ref(),
2266 &entry_name,
2267 &src_root,
2268 &dst_root,
2269 Some(&update_root),
2270 &entry_rel,
2271 UpdateRootRequirement::Optional,
2272 &settings,
2273 is_fresh,
2274 admission.into(),
2275 destination,
2276 )
2277 .await
2278 .map(|result| LinkTaskResult::from_link(entry_name, result));
2279 }
2280 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
2281 Err(error) => {
2282 return Err(Error::new(
2283 anyhow::Error::new(error).context(format!(
2284 "failed checking source counterpart for update entry {:?}",
2285 walk::join_rel(&src_root, &entry_rel)
2286 )),
2287 Default::default(),
2288 ));
2289 }
2290 }
2291 }
2292 process_update_only_entry(
2296 prog_track,
2297 update_parent,
2298 dst_parent,
2299 entry_name,
2300 update_entry_path,
2301 dst_root,
2302 entry_rel,
2303 destination,
2304 settings,
2305 is_fresh,
2306 admission,
2307 )
2308 .await
2309 };
2310 crate::task_scope::spawn_tracked(&mut join_set, do_copy());
2311 }
2312 }
2313 Ok::<(), anyhow::Error>(())
2314 }
2315 .await;
2316 if let Err(error) = enumeration_result {
2317 if settings.copy_settings.fail_early {
2318 crate::walk_driver::abort_and_join(&mut join_set).await;
2319 return Err(Error::new(error, link_summary));
2320 }
2321 outcomes.record_error(error);
2322 }
2323 while let Some(res) = join_set.join_next().await {
2324 if let Err(error) = fold_link_task_result(
2325 res,
2326 &mut link_summary,
2327 &mut outcomes,
2328 settings.copy_settings.fail_early,
2329 src_path,
2330 dst_path,
2331 ) {
2332 crate::walk_driver::abort_and_join(&mut join_set).await;
2333 return Err(Error::new(error, link_summary));
2334 }
2335 }
2336 let (decision, errors) = outcomes.finish();
2341 let delete_sources = match update_dir {
2342 Some(update_dir) if settings.update_exclusive => {
2343 crate::delete::DeleteSources::Single(update_dir)
2344 }
2345 Some(update_dir) => crate::delete::DeleteSources::Union(src_dir, update_dir),
2346 None => crate::delete::DeleteSources::Single(src_dir),
2347 };
2348 if let Some(keep_set) = decision.into_ready(dst_path)
2349 && let Some(prune_dir) = crate::delete::select_scan_dir(dst_dir, preview_dir, dst_path)
2350 && let Err(error) = crate::delete::prune_and_fold(
2351 prog_track,
2352 prune_dir,
2353 delete_sources,
2354 rel_path,
2355 &keep_set,
2356 settings.filter.as_ref(),
2357 settings.copy_settings.fail_early,
2358 settings.dry_run,
2359 &mut link_summary.copy_summary.rm_summary,
2360 Some(destination.protection()),
2361 )
2362 .await
2363 {
2364 if settings.copy_settings.fail_early {
2365 return Err(Error::new(error, link_summary));
2366 }
2367 errors.push(error);
2368 }
2369 let this_dir_count = usize::from(we_created_this_dir);
2372 let child_dirs_created = link_summary
2373 .copy_summary
2374 .directories_created
2375 .saturating_sub(this_dir_count);
2376 let anything_linked = link_summary.hard_links_created > 0
2377 || link_summary.copy_summary.files_copied > 0
2378 || link_summary.copy_summary.symlinks_created > 0
2379 || child_dirs_created > 0;
2380 match check_empty_dir_cleanup(
2381 settings.filter.as_ref(),
2382 we_created_this_dir,
2383 anything_linked,
2384 rel_path,
2385 settings.dry_run.is_some(),
2386 ) {
2387 EmptyDirAction::Keep => { }
2388 EmptyDirAction::DryRunSkip => {
2389 tracing::debug!(
2390 "dry-run: directory {:?} would not be created (nothing to link inside)",
2391 dst_path
2392 );
2393 link_summary.copy_summary.directories_created = 0;
2394 if errors.has_errors() {
2398 return Err(Error::new(errors.into_error().unwrap(), link_summary));
2399 }
2400 return Ok(link_summary);
2401 }
2402 EmptyDirAction::Remove => {
2403 tracing::debug!(
2404 "directory {:?} has nothing to link inside, removing empty directory",
2405 dst_path
2406 );
2407 if let Some(parent) = dst_parent {
2412 destination
2413 .protection()
2414 .check_child(parent, dst_name, dst_path)
2415 .await
2416 .map_err(|error| Error::new(error.into(), link_summary))?;
2417 }
2418 let rmdir_result = match dst_parent {
2419 Some(dst_parent) => dst_parent.rmdir_at(dst_name).await,
2420 None => {
2421 crate::walk::run_metadata_probed(
2422 congestion::Side::Destination,
2423 congestion::MetadataOp::RmDir,
2424 tokio::fs::remove_dir(dst_path),
2425 )
2426 .await
2427 }
2428 };
2429 match rmdir_result {
2430 Ok(()) => {
2431 link_summary.copy_summary.directories_created = 0;
2432 if errors.has_errors() {
2436 return Err(Error::new(errors.into_error().unwrap(), link_summary));
2437 }
2438 return Ok(link_summary);
2439 }
2440 Err(err) => {
2441 tracing::debug!(
2443 "failed to remove empty directory {:?}: {:#}, keeping",
2444 dst_path,
2445 &err
2446 );
2447 }
2449 }
2450 }
2451 }
2452 tracing::debug!("set 'dst' directory metadata");
2460 let metadata_result = match dst_dir {
2461 Some(dst_dir) => {
2462 crate::safedir::set_reused_dir_metadata_fd(
2463 &settings.preserve,
2464 &snapshot.meta,
2465 snapshot.acls.as_ref(),
2466 reused_lock,
2467 dst_dir,
2468 )
2469 .await
2470 }
2471 None => Ok(()),
2472 };
2473 if errors.has_errors() {
2474 if let Err(metadata_err) = metadata_result {
2476 tracing::error!(
2477 "link: {:?} -> {:?} failed to set directory metadata: {:#}",
2478 src_path,
2479 dst_path,
2480 &metadata_err
2481 );
2482 }
2483 return Err(Error::new(errors.into_error().unwrap(), link_summary));
2485 }
2486 metadata_result
2488 .with_context(|| format!("failed setting directory metadata on {:?}", dst_path))
2489 .map_err(|err| Error::new(err, link_summary))?;
2490 Ok(link_summary)
2491}
2492
2493#[cfg(test)]
2494#[allow(clippy::too_many_arguments)]
2495async fn link_dir_contents(
2496 prog_track: &'static progress::Progress,
2497 src_dir: &Arc<Dir>,
2498 preserve_meta: crate::safedir::FileMeta,
2499 update_dir: Option<&Arc<Dir>>,
2500 dst_dir: Option<&Arc<Dir>>,
2501 dst_parent: Option<&Arc<Dir>>,
2502 dst_name: &std::ffi::OsStr,
2503 src_root: &std::path::Path,
2504 dst_root: &std::path::Path,
2505 update_root: Option<&std::path::Path>,
2506 rel_path: &std::path::Path,
2507 src_path: &std::path::Path,
2508 dst_path: &std::path::Path,
2509 we_created_this_dir: bool,
2510 is_fresh: bool,
2511 reused_lock: Option<crate::safedir::ReusedDirLock>,
2512 settings: &Settings,
2513 base: Summary,
2514 source_entries: SourceEntries,
2515 update_entries: UpdateEntries,
2516 preview_dir: Option<&Arc<Dir>>,
2517 destination: copy::DestinationContext,
2518) -> Result<Summary, Error> {
2519 let snapshot = copy::SourceSnapshot::capture(
2520 update_dir.unwrap_or(src_dir),
2521 preserve_meta,
2522 settings.dry_run.is_none() && settings.preserve.dir.acl,
2523 )
2524 .await
2525 .map_err(|error| Error::new(error.into(), base))?;
2526 let destination = copy::destination::test_prepared(destination, dst_dir, preview_dir)
2527 .await
2528 .map_err(|error| Error::new(error, base))?;
2529 link_dir_contents_prepared(
2530 prog_track,
2531 src_dir,
2532 snapshot,
2533 update_dir,
2534 dst_dir,
2535 dst_parent,
2536 dst_name,
2537 src_root,
2538 dst_root,
2539 update_root,
2540 rel_path,
2541 src_path,
2542 dst_path,
2543 we_created_this_dir,
2544 is_fresh,
2545 reused_lock,
2546 settings,
2547 base,
2548 source_entries,
2549 update_entries,
2550 preview_dir,
2551 destination,
2552 )
2553 .await
2554}
2555
2556#[cfg(test)]
2557mod link_tests {
2558 use crate::rm;
2559 use crate::testutils;
2560 use std::os::unix::fs::PermissionsExt;
2561 use tracing_test::traced_test;
2562
2563 use super::*;
2564
2565 static PROGRESS: std::sync::LazyLock<progress::Progress> =
2566 std::sync::LazyLock::new(progress::Progress::new);
2567
2568 #[test]
2569 fn directory_close_primitive_drops_both_handles_before_permit() {
2570 let events = testutils::DropEvents::default();
2571 drop_link_handles_before_permit(
2572 events.probe("source handle"),
2573 Some(events.probe("update handle")),
2574 Some(events.probe("permit")),
2575 );
2576 assert_eq!(
2577 events.snapshot(),
2578 ["source handle", "update handle", "permit"]
2579 );
2580 }
2581
2582 #[test]
2583 fn admitted_link_entry_drops_both_handles_before_permit() {
2584 let events = testutils::DropEvents::default();
2585 let entry = AdmittedLinkEntry {
2586 src_handle: events.probe("source handle"),
2587 update_handle: Some(events.probe("update handle")),
2588 permit: Some(events.probe("permit")),
2589 };
2590 drop(entry);
2591 assert_eq!(
2592 events.snapshot(),
2593 ["source handle", "update handle", "permit"]
2594 );
2595 }
2596
2597 mod delete_keep_set_tests {
2598 use super::super::LinkChildOutcomes;
2602 use crate::copy::DeleteSettings;
2603 use std::ffi::{OsStr, OsString};
2604
2605 fn delete_on() -> DeleteSettings {
2606 DeleteSettings {
2607 delete_excluded: false,
2608 }
2609 }
2610
2611 #[test]
2612 fn exact_result_no_op_when_delete_off() {
2613 let mut k = LinkChildOutcomes::new(None);
2614 k.record_exact(OsString::from("foo"));
2615 assert!(k.as_set().is_none());
2616 }
2617
2618 #[test]
2619 fn exact_materialized_update_exclusive_duplicate_is_retained() {
2620 let d = delete_on();
2621 let mut k = LinkChildOutcomes::new(Some(&d));
2622 let mut summary = super::super::Summary::default();
2623 super::super::LinkTaskResult::from_link(
2624 OsString::from("node"),
2625 super::super::LinkEntryResult::selected(Default::default()),
2626 )
2627 .fold(&mut summary, &mut k);
2628 assert!(
2629 k.as_set().unwrap().contains(OsStr::new("node")),
2630 "the exact worker's materialized update selection must own the keep decision"
2631 );
2632 }
2633
2634 #[test]
2635 fn selected_source_entry_is_retained_in_normal_mode() {
2636 let d = delete_on();
2637 let mut k = LinkChildOutcomes::new(Some(&d));
2638 let mut summary = super::super::Summary::default();
2639 super::super::LinkTaskResult::from_link(
2640 OsString::from("node"),
2641 super::super::LinkEntryResult::selected(Default::default()),
2642 )
2643 .fold(&mut summary, &mut k);
2644 assert!(
2645 k.as_set().unwrap().contains(OsStr::new("node")),
2646 "the exact worker's selected source outcome must protect its destination"
2647 );
2648 }
2649
2650 #[test]
2651 fn full_directory_pass_keep_set_union_semantics() {
2652 let d = delete_on();
2661 let mut k = LinkChildOutcomes::new(Some(&d));
2662
2663 let mut summary = super::super::Summary::default();
2664 for name in ["keep", "pipe", "node"] {
2665 super::super::LinkTaskResult::from_link(
2666 OsString::from(name),
2667 super::super::LinkEntryResult::selected(Default::default()),
2668 )
2669 .fold(&mut summary, &mut k);
2670 }
2671 super::super::LinkTaskResult::from_update(
2672 OsString::from("from_upd"),
2673 super::super::LinkEntryResult::selected(Default::default()),
2674 )
2675 .fold(&mut summary, &mut k);
2676
2677 let set: std::collections::HashSet<OsString> = k.as_set().unwrap().clone();
2678 let expected: std::collections::HashSet<OsString> =
2679 ["keep", "pipe", "node", "from_upd"]
2680 .into_iter()
2681 .map(OsString::from)
2682 .collect();
2683 assert_eq!(set, expected);
2684 }
2685 }
2686
2687 #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
2688 #[tokio::test]
2689 async fn directory_acl_snapshot_precedes_child_traversal() -> anyhow::Result<()> {
2690 use crate::testutils::acl::*;
2691 for with_update in [false, true] {
2692 let root = tempfile::tempdir()?;
2693 let src = root.path().join("src");
2694 let update = root.path().join("update");
2695 let dst = root.path().join("dst");
2696 std::fs::create_dir_all(src.join("child"))?;
2697 std::fs::create_dir_all(update.join("child"))?;
2698 let chosen = if with_update { &update } else { &src };
2699 let acl = |permission| {
2700 encode_acl(&[
2701 (ACL_USER_OBJ, 7, ACL_UNDEFINED_ID),
2702 (ACL_USER, permission, nix::unistd::geteuid().as_raw()),
2703 (ACL_GROUP_OBJ, 0, ACL_UNDEFINED_ID),
2704 (ACL_MASK, 5, ACL_UNDEFINED_ID),
2705 (ACL_OTHER, 5, ACL_UNDEFINED_ID),
2706 ])
2707 };
2708 let original = acl(0);
2709 set_xattr_at(chosen, c"system.posix_acl_access", &original);
2710 let mut gate = testutils::BlockingPathGate::install(src.join("child"));
2711 let task_src = src.clone();
2712 let task_dst = dst.clone();
2713 let task_root = root.path().to_owned();
2714 let task_update = with_update.then_some(update.clone());
2715 let task = tokio::spawn(async move {
2716 let mut settings = common_settings(false, false);
2717 settings.preserve = preserve::preserve_all_with_acls();
2718 link(
2719 &PROGRESS,
2720 &task_root,
2721 &task_src,
2722 &task_dst,
2723 &task_update,
2724 &settings,
2725 false,
2726 )
2727 .await
2728 });
2729 tokio::time::timeout(std::time::Duration::from_secs(5), gate.wait_started()).await??;
2730 set_xattr_at(chosen, c"system.posix_acl_access", &acl(7));
2731 std::fs::set_permissions(chosen, std::fs::Permissions::from_mode(0o700))?;
2732 gate.release_all();
2733 task.await?.map_err(|error| error.source)?;
2734 assert_eq!(
2735 get_xattr_at(&dst, c"system.posix_acl_access"),
2736 Some(original)
2737 );
2738 assert_eq!(
2739 std::fs::metadata(&dst)?.permissions().mode() & 0o7777,
2740 0o755
2741 );
2742 }
2743 Ok(())
2744 }
2745
2746 mod delete_source_presence_tests {
2747 use super::*;
2748
2749 async fn link_with_omitted_source_names(
2750 root: &std::path::Path,
2751 settings: &Settings,
2752 with_update: bool,
2753 update_entries: Vec<(std::ffi::OsString, Option<EntryKind>)>,
2754 ) -> anyhow::Result<Summary> {
2755 let src = root.join("src");
2756 let update = root.join("update");
2757 let dst = root.join("dst");
2758 let src_dir =
2759 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
2760 let update_dir = if with_update {
2761 Some(Arc::new(
2762 Dir::open_root_dir(&update, false, congestion::Side::Source).await?,
2763 ))
2764 } else {
2765 None
2766 };
2767 let dst_dir =
2768 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
2769 let parent =
2770 Arc::new(Dir::open_root_dir(root, false, congestion::Side::Destination).await?);
2771 let preview = settings.dry_run.is_some();
2772 crate::task_scope::scope_tasks(link_dir_contents(
2773 &PROGRESS,
2774 &src_dir,
2775 update_dir.as_ref().unwrap_or(&src_dir).meta().await?,
2776 update_dir.as_ref(),
2777 (!preview).then_some(&dst_dir),
2778 (!preview).then_some(&parent),
2779 std::ffi::OsStr::new("dst"),
2780 &src,
2781 &dst,
2782 with_update.then_some(update.as_path()),
2783 std::path::Path::new(""),
2784 &src,
2785 &dst,
2786 false,
2787 false,
2788 None,
2789 settings,
2790 Summary::default(),
2791 SourceEntries::Injected(Vec::new()),
2792 UpdateEntries::Injected(update_entries),
2793 preview.then_some(&dst_dir),
2794 copy::DestinationContext::new(&dst),
2795 ))
2796 .await
2797 .map_err(|error| error.source)
2798 }
2799
2800 #[tokio::test]
2801 async fn delete_preserves_unlisted_names_from_the_selected_trees() -> anyhow::Result<()> {
2802 let limits = testutils::AdmissionLimit::new().await;
2803 limits.set_files_in_flight(1);
2804 for (with_update, exclusive) in
2805 [(false, false), (false, true), (true, false), (true, true)]
2806 {
2807 for preview in [false, true] {
2808 let root = tempfile::tempdir()?;
2809 for name in ["src", "update", "dst"] {
2810 tokio::fs::create_dir(root.path().join(name)).await?;
2811 }
2812 tokio::fs::write(root.path().join("src/source-only"), b"source").await?;
2813 tokio::fs::write(root.path().join("update/update-only"), b"update").await?;
2814 for name in ["source-only", "update-only", "extra"] {
2815 tokio::fs::write(root.path().join("dst").join(name), b"old").await?;
2816 }
2817 let mut settings = common_settings(false, true);
2818 settings.copy_settings.delete = Some(copy::DeleteSettings {
2819 delete_excluded: false,
2820 });
2821 settings.update_exclusive = exclusive;
2822 settings.filter = Some(crate::filter::FilterSettings::new());
2823 settings.copy_settings.filter = settings.filter.clone();
2824 settings.dry_run = preview.then_some(crate::config::DryRunMode::Brief);
2825 settings.copy_settings.dry_run = settings.dry_run;
2826 let summary = limits
2827 .run_with_timeout(
2828 std::time::Duration::from_secs(20),
2829 link_with_omitted_source_names(
2830 root.path(),
2831 &settings,
2832 with_update,
2833 Vec::new(),
2834 ),
2835 )
2836 .await??;
2837 let keep_source = !with_update || !exclusive;
2838 assert_eq!(
2839 root.path().join("dst/source-only").exists(),
2840 preview || keep_source,
2841 "with_update={with_update}, exclusive={exclusive}, preview={preview}"
2842 );
2843 assert_eq!(
2844 root.path().join("dst/update-only").exists(),
2845 preview || with_update
2846 );
2847 assert_eq!(root.path().join("dst/extra").exists(), preview);
2848 assert_eq!(
2849 summary.copy_summary.rm_summary.files_removed,
2850 1 + usize::from(!keep_source) + usize::from(!with_update)
2851 );
2852 }
2853 }
2854 Ok(())
2855 }
2856
2857 #[tokio::test]
2858 async fn delete_filters_unlisted_source_and_update_names_by_their_own_kinds()
2859 -> anyhow::Result<()> {
2860 for (source_is_dir, update_is_dir, exclusive, kept) in [
2861 (false, true, false, true),
2862 (false, true, true, false),
2863 (true, false, false, true),
2864 (true, false, true, true),
2865 (true, true, false, false),
2866 ] {
2867 let root = tempfile::tempdir()?;
2868 for (name, is_dir) in [("src", source_is_dir), ("update", update_is_dir)] {
2869 let parent = root.path().join(name);
2870 tokio::fs::create_dir(&parent).await?;
2871 if is_dir {
2872 tokio::fs::create_dir(parent.join("node")).await?;
2873 } else {
2874 tokio::fs::write(parent.join("node"), b"source").await?;
2875 }
2876 }
2877 tokio::fs::create_dir(root.path().join("dst")).await?;
2878 tokio::fs::write(root.path().join("dst/node"), b"old").await?;
2879 let mut filter = crate::filter::FilterSettings::new();
2880 filter.add_exclude("node/")?;
2881 let mut settings = common_settings(false, true);
2882 settings.copy_settings.delete = Some(copy::DeleteSettings {
2883 delete_excluded: true,
2884 });
2885 settings.filter = Some(filter.clone());
2886 settings.copy_settings.filter = Some(filter);
2887 settings.update_exclusive = exclusive;
2888 let summary =
2889 link_with_omitted_source_names(root.path(), &settings, true, Vec::new())
2890 .await?;
2891 assert_eq!(
2892 root.path().join("dst/node").exists(),
2893 kept,
2894 "source_dir={source_is_dir}, update_dir={update_is_dir}, exclusive={exclusive}"
2895 );
2896 assert_eq!(
2897 summary.copy_summary.rm_summary.files_removed,
2898 usize::from(!kept)
2899 );
2900 }
2901 Ok(())
2902 }
2903
2904 #[tokio::test]
2905 async fn delete_merges_an_unlisted_source_directory_with_update() -> anyhow::Result<()> {
2906 let limits = testutils::AdmissionLimit::new().await;
2907 limits.set_files_in_flight(1);
2908 for exclusive in [false, true] {
2909 let root = tempfile::tempdir()?;
2910 for name in ["src/node", "update/node", "dst/node"] {
2911 tokio::fs::create_dir_all(root.path().join(name)).await?;
2912 }
2913 tokio::fs::write(root.path().join("src/node/source-only"), b"source").await?;
2914 tokio::fs::write(root.path().join("update/node/update-only"), b"update").await?;
2915 tokio::fs::write(root.path().join("dst/node/source-only"), b"old").await?;
2916 tokio::fs::write(root.path().join("dst/node/extra"), b"remove").await?;
2917 let mut settings = common_settings(false, true);
2918 settings.copy_settings.delete = Some(copy::DeleteSettings {
2919 delete_excluded: false,
2920 });
2921 settings.update_exclusive = exclusive;
2922 limits
2923 .run_with_timeout(
2924 std::time::Duration::from_secs(20),
2925 link_with_omitted_source_names(
2926 root.path(),
2927 &settings,
2928 true,
2929 vec![(std::ffi::OsString::from("node"), Some(EntryKind::Dir))],
2930 ),
2931 )
2932 .await??;
2933 assert_eq!(
2934 root.path().join("dst/node/source-only").exists(),
2935 !exclusive,
2936 "the source listing omitted node; exclusive={exclusive}"
2937 );
2938 if !exclusive {
2939 assert_eq!(
2940 tokio::fs::read(root.path().join("dst/node/source-only")).await?,
2941 b"source"
2942 );
2943 }
2944 assert_eq!(
2945 tokio::fs::read(root.path().join("dst/node/update-only")).await?,
2946 b"update"
2947 );
2948 assert!(!root.path().join("dst/node/extra").exists());
2949 }
2950 Ok(())
2951 }
2952 }
2953
2954 fn common_settings(dereference: bool, overwrite: bool) -> Settings {
2955 Settings {
2956 copy_settings: CopySettings {
2957 reflink: Default::default(),
2958 local_copy_handoff: Default::default(),
2959 dereference,
2960 fail_early: false,
2961 overwrite,
2962 overwrite_compare: filecmp::MetadataCmpSettings {
2963 size: true,
2964 mtime: true,
2965 ..Default::default()
2966 },
2967 overwrite_filter: None,
2968 ignore_existing: false,
2969 chunk_size: 0,
2970 skip_specials: false,
2971 remote_copy_buffer_size: 0,
2972 filter: None,
2973 dry_run: None,
2974 delete: None,
2975 },
2976 update_compare: filecmp::MetadataCmpSettings {
2977 size: true,
2978 mtime: true,
2979 ..Default::default()
2980 },
2981 update_exclusive: false,
2982 filter: None,
2983 dry_run: None,
2984 preserve: preserve::preserve_all(),
2985 }
2986 }
2987
2988 async fn check_rejected_input_destination(
2989 in_update: bool,
2990 exclusive: bool,
2991 ) -> anyhow::Result<()> {
2992 for preview in [false, true] {
2993 let root = tempfile::tempdir()?;
2994 let src = root.path().join("src");
2995 let update = root.path().join("update");
2996 for input in [&src, &update] {
2997 tokio::fs::create_dir(input).await?;
2998 let mut config = crate::filegen::FileGenConfig::new(input, vec![], 1, 32);
2999 config.leaf_files = true;
3000 crate::filegen::filegen(&PROGRESS, &config).await?;
3001 }
3002 let dst = if in_update { &update } else { &src }.join("dst");
3003 let mut filter = crate::filter::FilterSettings::new();
3004 filter.add_exclude("dst/")?;
3006 let mut settings = common_settings(false, true);
3007 settings.filter = Some(filter.clone());
3008 settings.copy_settings.filter = Some(filter);
3009 settings.update_exclusive = exclusive;
3010 settings.dry_run = preview.then_some(crate::config::DryRunMode::Brief);
3011 settings.copy_settings.dry_run = settings.dry_run;
3012 let error = link(
3013 &PROGRESS,
3014 root.path(),
3015 &src,
3016 &dst,
3017 &Some(update.clone()),
3018 &settings,
3019 false,
3020 )
3021 .await
3022 .expect_err("a destination inside a source or update root must be rejected");
3023 assert!(format!("{:#}", error.source).contains("overlap"));
3024 assert_eq!(error.summary.copy_summary.directories_created, 0);
3025 assert!(!dst.exists());
3026 assert_eq!(tokio::fs::metadata(src.join("file0")).await?.len(), 32);
3027 assert_eq!(tokio::fs::metadata(update.join("file0")).await?.len(), 32);
3028 }
3029 Ok(())
3030 }
3031
3032 #[tokio::test]
3033 async fn rejects_destination_inside_link_source_before_creating_it() -> anyhow::Result<()> {
3034 check_rejected_input_destination(false, false).await
3035 }
3036
3037 #[tokio::test]
3038 async fn rejects_destination_inside_update_before_creating_it() -> anyhow::Result<()> {
3039 for exclusive in [false, true] {
3040 check_rejected_input_destination(true, exclusive).await?;
3041 }
3042 Ok(())
3043 }
3044
3045 struct RestoreRenamedUpdateRoot {
3046 original: std::path::PathBuf,
3047 renamed: std::path::PathBuf,
3048 }
3049
3050 impl Drop for RestoreRenamedUpdateRoot {
3051 fn drop(&mut self) {
3052 if self.renamed.exists() {
3053 let _ = std::fs::rename(&self.renamed, &self.original);
3054 }
3055 }
3056 }
3057
3058 struct DisappearingUpdateRootHook {
3059 _registration: AfterUpdatePrecheckHookRegistration,
3060 _cleanup: std::sync::Arc<std::sync::Mutex<Option<RestoreRenamedUpdateRoot>>>,
3061 }
3062
3063 fn disappear_update_root_after_precheck(
3064 update: &std::path::Path,
3065 ) -> DisappearingUpdateRootHook {
3066 let original = update.to_owned();
3067 let renamed = update.with_extension("removed-after-precheck");
3068 let cleanup = std::sync::Arc::new(std::sync::Mutex::new(None));
3069 let hook_cleanup = Arc::clone(&cleanup);
3070 let registration = install_after_update_precheck_hook(
3071 original.clone(),
3072 Box::new(move || {
3073 std::fs::rename(&original, &renamed)
3074 .expect("rename update root after its early precheck");
3075 *hook_cleanup
3076 .lock()
3077 .unwrap_or_else(std::sync::PoisonError::into_inner) =
3078 Some(RestoreRenamedUpdateRoot { original, renamed });
3079 }),
3080 );
3081 DisappearingUpdateRootHook {
3082 _registration: registration,
3083 _cleanup: cleanup,
3084 }
3085 }
3086
3087 async fn setup_disappearing_update_root_case() -> Result<
3088 (
3089 std::path::PathBuf,
3090 std::path::PathBuf,
3091 std::path::PathBuf,
3092 std::path::PathBuf,
3093 ),
3094 anyhow::Error,
3095 > {
3096 let test_path = testutils::create_temp_dir().await?;
3097 let src = test_path.join("src");
3098 let update = test_path.join("update");
3099 let dst = test_path.join("dst");
3100 tokio::fs::create_dir(&src).await?;
3101 tokio::fs::create_dir(&update).await?;
3102 tokio::fs::create_dir(&dst).await?;
3103 tokio::fs::write(src.join("source-only.txt"), "SOURCE").await?;
3104 tokio::fs::write(update.join("protected.txt"), "UPDATE").await?;
3105 tokio::fs::write(dst.join("source-only.txt"), "DESTINATION").await?;
3106 tokio::fs::write(dst.join("protected.txt"), "PROTECTED DESTINATION").await?;
3107 Ok((test_path, src, update, dst))
3108 }
3109
3110 fn assert_missing_destructive_update_error(error: &Error) {
3111 let message = format!("{:#}", error.source);
3112 assert!(
3113 message.contains("--update path") && message.contains("does not exist"),
3114 "missing destructive update error was unclear: {message}"
3115 );
3116 }
3117
3118 #[tokio::test]
3119 async fn update_exclusive_errors_if_update_root_disappears_after_precheck()
3120 -> Result<(), anyhow::Error> {
3121 let (test_path, src, update, dst) = setup_disappearing_update_root_case().await?;
3122 let _hook = disappear_update_root_after_precheck(&update);
3123 let mut settings = common_settings(false, true);
3124 settings.update_exclusive = true;
3125 let result = link(
3126 &PROGRESS,
3127 &test_path,
3128 &src,
3129 &dst,
3130 &Some(update.clone()),
3131 &settings,
3132 false,
3133 )
3134 .await;
3135 assert_eq!(
3136 tokio::fs::read_to_string(dst.join("source-only.txt")).await?,
3137 "DESTINATION"
3138 );
3139 assert_eq!(
3140 tokio::fs::read_to_string(dst.join("protected.txt")).await?,
3141 "PROTECTED DESTINATION"
3142 );
3143 let error = result.expect_err("a vanished update root must fail update-exclusive");
3144 assert_missing_destructive_update_error(&error);
3145 Ok(())
3146 }
3147
3148 #[tokio::test]
3149 async fn delete_update_does_not_prune_if_update_root_disappears_after_precheck()
3150 -> Result<(), anyhow::Error> {
3151 let (test_path, src, update, dst) = setup_disappearing_update_root_case().await?;
3152 let _hook = disappear_update_root_after_precheck(&update);
3153 let mut settings = common_settings(false, true);
3154 settings.copy_settings.delete = Some(copy::DeleteSettings {
3155 delete_excluded: false,
3156 });
3157 settings.filter = Some(crate::filter::FilterSettings::new());
3158 let result = link(
3159 &PROGRESS,
3160 &test_path,
3161 &src,
3162 &dst,
3163 &Some(update.clone()),
3164 &settings,
3165 false,
3166 )
3167 .await;
3168 assert_eq!(
3169 tokio::fs::read_to_string(dst.join("source-only.txt")).await?,
3170 "DESTINATION"
3171 );
3172 assert_eq!(
3173 tokio::fs::read_to_string(dst.join("protected.txt")).await?,
3174 "PROTECTED DESTINATION"
3175 );
3176 let error = result.expect_err("a vanished update root must stop delete pruning");
3177 assert_missing_destructive_update_error(&error);
3178 Ok(())
3179 }
3180
3181 #[tokio::test]
3182 async fn plain_update_falls_back_if_update_root_disappears_after_precheck()
3183 -> Result<(), anyhow::Error> {
3184 let (test_path, src, update, dst) = setup_disappearing_update_root_case().await?;
3185 let _hook = disappear_update_root_after_precheck(&update);
3186 link(
3187 &PROGRESS,
3188 &test_path,
3189 &src,
3190 &dst,
3191 &Some(update),
3192 &common_settings(false, true),
3193 false,
3194 )
3195 .await?;
3196 assert_eq!(
3197 tokio::fs::read_to_string(dst.join("source-only.txt")).await?,
3198 "SOURCE"
3199 );
3200 assert_eq!(
3201 tokio::fs::read_to_string(dst.join("protected.txt")).await?,
3202 "PROTECTED DESTINATION"
3203 );
3204 Ok(())
3205 }
3206
3207 #[tokio::test]
3208 async fn renamed_non_utf8_file_roots_keep_destination_basename() -> anyhow::Result<()> {
3209 use std::os::unix::ffi::OsStrExt;
3210 use std::os::unix::fs::MetadataExt;
3211 for with_update in [false, true] {
3212 let root = testutils::create_temp_dir().await?;
3213 let src = root.join(std::ffi::OsStr::from_bytes(b"source\xff"));
3214 let dst = root.join(std::ffi::OsStr::from_bytes(b"renamed\xfe"));
3215 let update = root.join(std::ffi::OsStr::from_bytes(b"update\xfd"));
3216 tokio::fs::write(&src, b"source").await?;
3217 tokio::fs::write(&update, b"updated contents").await?;
3218 let summary = link(
3219 &PROGRESS,
3220 &root,
3221 &src,
3222 &dst,
3223 &with_update.then_some(update),
3224 &common_settings(false, false),
3225 false,
3226 )
3227 .await?;
3228 assert_eq!(
3229 tokio::fs::read(&dst).await?,
3230 if with_update {
3231 b"updated contents".as_slice()
3232 } else {
3233 b"source"
3234 }
3235 );
3236 assert_eq!(summary.hard_links_created, usize::from(!with_update));
3237 assert_eq!(summary.copy_summary.files_copied, usize::from(with_update));
3238 let src_meta = tokio::fs::metadata(&src).await?;
3239 let dst_meta = tokio::fs::metadata(&dst).await?;
3240 assert_eq!(
3241 (src_meta.dev(), src_meta.ino()) == (dst_meta.dev(), dst_meta.ino()),
3242 !with_update
3243 );
3244 }
3245 Ok(())
3246 }
3247
3248 #[tokio::test]
3249 async fn invalid_destination_root_is_rejected_before_source_classification()
3250 -> anyhow::Result<()> {
3251 let root = testutils::create_temp_dir().await?;
3252 let dir = Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Source).await?);
3253 let source = root.join("missing-source");
3254 let destination = std::path::Path::new("/");
3255 let result = link_internal(
3256 &PROGRESS,
3257 &dir,
3258 None,
3259 None,
3260 std::ffi::OsStr::new("missing-source"),
3261 &source,
3262 destination,
3263 None,
3264 std::path::Path::new(""),
3265 UpdateRootRequirement::Optional,
3266 &common_settings(false, false),
3267 false,
3268 EntryAdmission::RootOrDelegated.into(),
3269 copy::DestinationContext::new(destination),
3270 )
3271 .await;
3272 let error = match result {
3273 Ok(_) => panic!("invalid destination must fail"),
3274 Err(error) => error,
3275 };
3276 assert!(format!("{:#}", error.source).contains("has no file name"));
3277 assert!(!source.exists());
3278 Ok(())
3279 }
3280
3281 #[tokio::test]
3282 async fn update_exclusive_without_update_links_the_source_normally() -> Result<(), anyhow::Error>
3283 {
3284 use std::os::unix::fs::MetadataExt;
3285 let test_path = testutils::create_temp_dir().await?;
3286 let src = test_path.join("src");
3287 let dst = test_path.join("dst");
3288 tokio::fs::write(&src, "SOURCE").await?;
3289 let mut settings = common_settings(false, false);
3290 settings.update_exclusive = true;
3291 let summary = link(&PROGRESS, &test_path, &src, &dst, &None, &settings, false).await?;
3292 assert_eq!(summary.hard_links_created, 1);
3293 assert_eq!(tokio::fs::read_to_string(&dst).await?, "SOURCE");
3294 let src_metadata = tokio::fs::metadata(&src).await?;
3295 let dst_metadata = tokio::fs::metadata(&dst).await?;
3296 assert_eq!(
3297 (src_metadata.dev(), src_metadata.ino()),
3298 (dst_metadata.dev(), dst_metadata.ino())
3299 );
3300 Ok(())
3301 }
3302
3303 #[tokio::test]
3304 #[traced_test]
3305 async fn test_basic_link() -> Result<(), anyhow::Error> {
3306 let tmp_dir = testutils::setup_test_dir().await?;
3307 let test_path = tmp_dir.as_path();
3308 let summary = link(
3309 &PROGRESS,
3310 test_path,
3311 &test_path.join("foo"),
3312 &test_path.join("bar"),
3313 &None,
3314 &common_settings(false, false),
3315 false,
3316 )
3317 .await?;
3318 assert_eq!(summary.hard_links_created, 5);
3319 assert_eq!(summary.copy_summary.files_copied, 0);
3320 assert_eq!(summary.copy_summary.symlinks_created, 2);
3321 assert_eq!(summary.copy_summary.directories_created, 3);
3322 testutils::check_dirs_identical(
3323 &test_path.join("foo"),
3324 &test_path.join("bar"),
3325 testutils::FileEqualityCheck::Timestamp,
3326 )
3327 .await?;
3328 Ok(())
3329 }
3330
3331 #[tokio::test]
3332 async fn nested_non_utf8_names_keep_source_and_update_outcomes_during_delete()
3333 -> anyhow::Result<()> {
3334 use std::os::unix::ffi::OsStrExt;
3335 use std::os::unix::fs::MetadataExt;
3336 let branch = std::ffi::OsStr::from_bytes(b"branch\xff");
3337 let shared_name = std::ffi::OsStr::from_bytes(b"shared\xfe");
3338 let source_name = std::ffi::OsStr::from_bytes(b"source\xfd");
3339 let update_name = std::ffi::OsStr::from_bytes(b"update\xfc");
3340 for with_update in [false, true] {
3341 let root = testutils::create_temp_dir().await?;
3342 let src = root.join("src");
3343 let update = root.join("update");
3344 let dst = root.join("dst");
3345 let src_branch = src.join(branch);
3346 let update_branch = update.join(branch);
3347 let dst_branch = dst.join(branch);
3348 tokio::fs::create_dir_all(&src_branch).await?;
3349 tokio::fs::create_dir_all(&update_branch).await?;
3350 tokio::fs::create_dir_all(&dst_branch).await?;
3351 tokio::fs::write(src_branch.join(shared_name), b"original").await?;
3352 tokio::fs::write(src_branch.join(source_name), b"source only").await?;
3353 tokio::fs::write(update_branch.join(shared_name), b"updated contents").await?;
3354 tokio::fs::write(update_branch.join(update_name), b"update only").await?;
3355 tokio::fs::write(dst_branch.join("stale"), b"stale").await?;
3356 let mut settings = common_settings(false, true);
3357 settings.copy_settings.delete = Some(copy::DeleteSettings {
3358 delete_excluded: false,
3359 });
3360 let summary = link(
3361 &PROGRESS,
3362 &root,
3363 &src,
3364 &dst,
3365 &with_update.then_some(update),
3366 &settings,
3367 false,
3368 )
3369 .await?;
3370 assert_eq!(summary.hard_links_created, if with_update { 1 } else { 2 });
3371 assert_eq!(
3372 summary.copy_summary.files_copied,
3373 if with_update { 2 } else { 0 }
3374 );
3375 assert_eq!(summary.copy_summary.rm_summary.files_removed, 1);
3376 assert!(!dst_branch.join("stale").exists());
3377 assert_eq!(
3378 tokio::fs::read(dst_branch.join(shared_name)).await?,
3379 if with_update {
3380 b"updated contents".as_slice()
3381 } else {
3382 b"original"
3383 }
3384 );
3385 assert_eq!(
3386 tokio::fs::read(dst_branch.join(source_name)).await?,
3387 b"source only"
3388 );
3389 let src_meta = tokio::fs::metadata(src_branch.join(source_name)).await?;
3390 let dst_meta = tokio::fs::metadata(dst_branch.join(source_name)).await?;
3391 assert_eq!(
3392 (src_meta.dev(), src_meta.ino()),
3393 (dst_meta.dev(), dst_meta.ino())
3394 );
3395 if with_update {
3396 assert_eq!(
3397 tokio::fs::read(dst_branch.join(update_name)).await?,
3398 b"update only"
3399 );
3400 } else {
3401 assert!(!dst_branch.join(update_name).exists());
3402 }
3403 tokio::fs::remove_dir_all(root).await?;
3404 }
3405 Ok(())
3406 }
3407
3408 #[tokio::test]
3412 async fn links_dot_dot_source_operand() -> Result<(), anyhow::Error> {
3413 use std::os::unix::fs::MetadataExt;
3414 let tmp = testutils::create_temp_dir().await?;
3415 let tree = tmp.join("tree");
3416 tokio::fs::create_dir(&tree).await?;
3417 tokio::fs::write(tree.join("a.txt"), "hello").await?;
3418 tokio::fs::create_dir(tree.join("sub")).await?;
3419 let src = tree.join("sub").join(".."); let dst = tmp.join("dst");
3421 let summary = link(
3422 &PROGRESS,
3423 &tmp,
3424 &src,
3425 &dst,
3426 &None,
3427 &common_settings(false, false),
3428 false,
3429 )
3430 .await?;
3431 assert_eq!(
3432 summary.hard_links_created, 1,
3433 "the dot-dot source's file must be hard-linked"
3434 );
3435 assert!(
3436 dst.join("sub").is_dir(),
3437 "the dot-dot source's subdir must be created"
3438 );
3439 let src_ino = std::fs::metadata(tree.join("a.txt"))?.ino();
3441 let dst_ino = std::fs::metadata(dst.join("a.txt"))?.ino();
3442 assert_eq!(src_ino, dst_ino, "dst must be a hard link to the src inode");
3443 Ok(())
3444 }
3445
3446 #[tokio::test]
3452 async fn links_dot_dot_update_operand() -> Result<(), anyhow::Error> {
3453 use std::os::unix::fs::MetadataExt;
3454 let tmp = testutils::create_temp_dir().await?;
3455 let tree = tmp.join("tree");
3456 tokio::fs::create_dir(&tree).await?;
3457 tokio::fs::write(tree.join("a.txt"), "hello").await?;
3458 tokio::fs::create_dir(tree.join("sub")).await?;
3459 let dst = tmp.join("dst");
3460 let update_operand = tree.join("sub").join(".."); let summary = link(
3464 &PROGRESS,
3465 &tmp,
3466 &tree,
3467 &dst,
3468 &Some(update_operand),
3469 &common_settings(false, false),
3470 false,
3471 )
3472 .await?;
3473 assert_eq!(
3474 summary.hard_links_created, 1,
3475 "the file must be hard-linked from the dot-dot update tree"
3476 );
3477 let update_ino = std::fs::metadata(tree.join("a.txt"))?.ino();
3479 let dst_ino = std::fs::metadata(dst.join("a.txt"))?.ino();
3480 assert_eq!(
3481 update_ino, dst_ino,
3482 "dst must be hard-linked from the update tree inode"
3483 );
3484 Ok(())
3485 }
3486
3487 #[tokio::test]
3488 #[traced_test]
3489 async fn test_basic_link_update() -> Result<(), anyhow::Error> {
3490 let tmp_dir = testutils::setup_test_dir().await?;
3491 let test_path = tmp_dir.as_path();
3492 let summary = link(
3493 &PROGRESS,
3494 test_path,
3495 &test_path.join("foo"),
3496 &test_path.join("bar"),
3497 &Some(test_path.join("foo")),
3498 &common_settings(false, false),
3499 false,
3500 )
3501 .await?;
3502 assert_eq!(summary.hard_links_created, 5);
3503 assert_eq!(summary.copy_summary.files_copied, 0);
3504 assert_eq!(summary.copy_summary.symlinks_created, 2);
3505 assert_eq!(summary.copy_summary.directories_created, 3);
3506 testutils::check_dirs_identical(
3507 &test_path.join("foo"),
3508 &test_path.join("bar"),
3509 testutils::FileEqualityCheck::Timestamp,
3510 )
3511 .await?;
3512 Ok(())
3513 }
3514
3515 #[tokio::test]
3516 #[traced_test]
3517 async fn test_basic_link_empty_src() -> Result<(), anyhow::Error> {
3518 let tmp_dir = testutils::setup_test_dir().await?;
3519 tokio::fs::create_dir(tmp_dir.join("baz")).await?;
3520 let test_path = tmp_dir.as_path();
3521 let summary = link(
3522 &PROGRESS,
3523 test_path,
3524 &test_path.join("baz"), &test_path.join("bar"),
3526 &Some(test_path.join("foo")),
3527 &common_settings(false, false),
3528 false,
3529 )
3530 .await?;
3531 assert_eq!(summary.hard_links_created, 0);
3532 assert_eq!(summary.copy_summary.files_copied, 5);
3533 assert_eq!(summary.copy_summary.symlinks_created, 2);
3534 assert_eq!(summary.copy_summary.directories_created, 3);
3535 testutils::check_dirs_identical(
3536 &test_path.join("foo"),
3537 &test_path.join("bar"),
3538 testutils::FileEqualityCheck::Timestamp,
3539 )
3540 .await?;
3541 Ok(())
3542 }
3543
3544 #[tokio::test]
3545 #[traced_test]
3546 async fn test_link_destination_permission_error_includes_root_cause()
3547 -> Result<(), anyhow::Error> {
3548 let tmp_dir = testutils::setup_test_dir().await?;
3549 let test_path = tmp_dir.as_path();
3550 let readonly_parent = test_path.join("readonly_dest");
3551 tokio::fs::create_dir(&readonly_parent).await?;
3552 tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o555))
3553 .await?;
3554
3555 let mut settings = common_settings(false, false);
3556 settings.copy_settings.fail_early = true;
3557
3558 let result = link(
3559 &PROGRESS,
3560 test_path,
3561 &test_path.join("foo"),
3562 &readonly_parent.join("bar"),
3563 &None,
3564 &settings,
3565 false,
3566 )
3567 .await;
3568
3569 tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o755))
3571 .await?;
3572
3573 assert!(result.is_err(), "link into read-only parent should fail");
3574 let err = result.unwrap_err();
3575 let err_msg = format!("{:#}", err.source);
3576 assert!(
3577 err_msg.to_lowercase().contains("permission denied") || err_msg.contains("EACCES"),
3578 "Error message must include permission denied text. Got: {}",
3579 err_msg
3580 );
3581 Ok(())
3582 }
3583
3584 #[tokio::test]
3585 #[traced_test]
3586 async fn hard_link_file_into_readonly_parent_returns_error() -> Result<(), anyhow::Error> {
3587 let tmp_dir = testutils::setup_test_dir().await?;
3590 let src = tmp_dir.join("src.txt");
3591 tokio::fs::write(&src, "content").await?;
3592 let readonly_parent = tmp_dir.join("readonly_parent");
3593 tokio::fs::create_dir(&readonly_parent).await?;
3594 tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o555))
3595 .await?;
3596 let dst = readonly_parent.join("dst.txt");
3597 let settings = common_settings(false, false);
3598 let result = link(&PROGRESS, &tmp_dir, &src, &dst, &None, &settings, false).await;
3599 tokio::fs::set_permissions(&readonly_parent, std::fs::Permissions::from_mode(0o755))
3600 .await?;
3601 let err = result.expect_err("link into read-only parent should fail");
3602 assert_eq!(err.summary.hard_links_created, 0);
3603 let err_msg = format!("{:#}", err.source);
3604 assert!(
3605 err_msg.to_lowercase().contains("permission denied") || err_msg.contains("EACCES"),
3606 "error should include root cause, got: {err_msg}"
3607 );
3608 Ok(())
3609 }
3610
3611 pub async fn setup_update_dir(tmp_dir: &std::path::Path) -> Result<(), anyhow::Error> {
3612 let foo_path = tmp_dir.join("update");
3618 tokio::fs::create_dir(&foo_path).await.unwrap();
3619 tokio::fs::write(foo_path.join("0.txt"), "0-new")
3620 .await
3621 .unwrap();
3622 let bar_path = foo_path.join("bar");
3623 tokio::fs::create_dir(&bar_path).await.unwrap();
3624 tokio::fs::write(bar_path.join("1.txt"), "1-new")
3625 .await
3626 .unwrap();
3627 tokio::fs::symlink("../1.txt", bar_path.join("2.txt"))
3628 .await
3629 .unwrap();
3630 tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
3631 Ok(())
3632 }
3633
3634 #[tokio::test]
3635 #[traced_test]
3636 async fn test_link_update() -> Result<(), anyhow::Error> {
3637 let tmp_dir = testutils::setup_test_dir().await?;
3638 setup_update_dir(&tmp_dir).await?;
3639 let test_path = tmp_dir.as_path();
3640 let summary = link(
3641 &PROGRESS,
3642 test_path,
3643 &test_path.join("foo"),
3644 &test_path.join("bar"),
3645 &Some(test_path.join("update")),
3646 &common_settings(false, false),
3647 false,
3648 )
3649 .await?;
3650 assert_eq!(summary.hard_links_created, 2);
3651 assert_eq!(summary.copy_summary.files_copied, 2);
3652 assert_eq!(summary.copy_summary.symlinks_created, 3);
3653 assert_eq!(summary.copy_summary.directories_created, 3);
3654 testutils::check_dirs_identical(
3656 &test_path.join("foo").join("baz"),
3657 &test_path.join("bar").join("baz"),
3658 testutils::FileEqualityCheck::HardLink,
3659 )
3660 .await?;
3661 testutils::check_dirs_identical(
3663 &test_path.join("update"),
3664 &test_path.join("bar"),
3665 testutils::FileEqualityCheck::Timestamp,
3666 )
3667 .await?;
3668 Ok(())
3669 }
3670
3671 #[tokio::test]
3672 #[traced_test]
3673 async fn test_link_update_exclusive() -> Result<(), anyhow::Error> {
3674 let tmp_dir = testutils::setup_test_dir().await?;
3675 setup_update_dir(&tmp_dir).await?;
3676 let test_path = tmp_dir.as_path();
3677 let mut settings = common_settings(false, false);
3678 settings.update_exclusive = true;
3679 let summary = link(
3680 &PROGRESS,
3681 test_path,
3682 &test_path.join("foo"),
3683 &test_path.join("bar"),
3684 &Some(test_path.join("update")),
3685 &settings,
3686 false,
3687 )
3688 .await?;
3689 assert_eq!(summary.hard_links_created, 0);
3695 assert_eq!(summary.copy_summary.files_copied, 2);
3696 assert_eq!(summary.copy_summary.symlinks_created, 1);
3697 assert_eq!(summary.copy_summary.directories_created, 2);
3698 testutils::check_dirs_identical(
3700 &test_path.join("update"),
3701 &test_path.join("bar"),
3702 testutils::FileEqualityCheck::Timestamp,
3703 )
3704 .await?;
3705 Ok(())
3706 }
3707
3708 async fn setup_test_dir_and_link() -> Result<std::path::PathBuf, anyhow::Error> {
3709 let tmp_dir = testutils::setup_test_dir().await?;
3710 let test_path = tmp_dir.as_path();
3711 let summary = link(
3712 &PROGRESS,
3713 test_path,
3714 &test_path.join("foo"),
3715 &test_path.join("bar"),
3716 &None,
3717 &common_settings(false, false),
3718 false,
3719 )
3720 .await?;
3721 assert_eq!(summary.hard_links_created, 5);
3722 assert_eq!(summary.copy_summary.symlinks_created, 2);
3723 assert_eq!(summary.copy_summary.directories_created, 3);
3724 Ok(tmp_dir)
3725 }
3726
3727 #[tokio::test]
3728 #[traced_test]
3729 async fn test_link_overwrite_basic() -> Result<(), anyhow::Error> {
3730 let tmp_dir = setup_test_dir_and_link().await?;
3731 let output_path = &tmp_dir.join("bar");
3732 {
3733 let summary = rm::rm(
3744 &PROGRESS,
3745 &output_path.join("bar"),
3746 &rm::Settings {
3747 fail_early: false,
3748 filter: None,
3749 dry_run: None,
3750 time_filter: None,
3751 },
3752 )
3753 .await?
3754 + rm::rm(
3755 &PROGRESS,
3756 &output_path.join("baz").join("5.txt"),
3757 &rm::Settings {
3758 fail_early: false,
3759 filter: None,
3760 dry_run: None,
3761 time_filter: None,
3762 },
3763 )
3764 .await?;
3765 assert_eq!(summary.files_removed, 3);
3766 assert_eq!(summary.symlinks_removed, 1);
3767 assert_eq!(summary.directories_removed, 1);
3768 }
3769 let summary = link(
3770 &PROGRESS,
3771 &tmp_dir,
3772 &tmp_dir.join("foo"),
3773 output_path,
3774 &None,
3775 &common_settings(false, true), false,
3777 )
3778 .await?;
3779 assert_eq!(summary.hard_links_created, 3);
3780 assert_eq!(summary.copy_summary.symlinks_created, 1);
3781 assert_eq!(summary.copy_summary.directories_created, 1);
3782 testutils::check_dirs_identical(
3783 &tmp_dir.join("foo"),
3784 output_path,
3785 testutils::FileEqualityCheck::Timestamp,
3786 )
3787 .await?;
3788 Ok(())
3789 }
3790
3791 #[tokio::test]
3792 #[traced_test]
3793 async fn test_link_update_overwrite_basic() -> Result<(), anyhow::Error> {
3794 let tmp_dir = setup_test_dir_and_link().await?;
3795 let output_path = &tmp_dir.join("bar");
3796 {
3797 let summary = rm::rm(
3808 &PROGRESS,
3809 &output_path.join("bar"),
3810 &rm::Settings {
3811 fail_early: false,
3812 filter: None,
3813 dry_run: None,
3814 time_filter: None,
3815 },
3816 )
3817 .await?
3818 + rm::rm(
3819 &PROGRESS,
3820 &output_path.join("baz").join("5.txt"),
3821 &rm::Settings {
3822 fail_early: false,
3823 filter: None,
3824 dry_run: None,
3825 time_filter: None,
3826 },
3827 )
3828 .await?;
3829 assert_eq!(summary.files_removed, 3);
3830 assert_eq!(summary.symlinks_removed, 1);
3831 assert_eq!(summary.directories_removed, 1);
3832 }
3833 setup_update_dir(&tmp_dir).await?;
3834 let summary = link(
3840 &PROGRESS,
3841 &tmp_dir,
3842 &tmp_dir.join("foo"),
3843 output_path,
3844 &Some(tmp_dir.join("update")),
3845 &common_settings(false, true), false,
3847 )
3848 .await?;
3849 assert_eq!(summary.hard_links_created, 1); assert_eq!(summary.copy_summary.files_copied, 2); assert_eq!(summary.copy_summary.symlinks_created, 2); assert_eq!(summary.copy_summary.directories_created, 1);
3853 testutils::check_dirs_identical(
3855 &tmp_dir.join("foo").join("baz"),
3856 &tmp_dir.join("bar").join("baz"),
3857 testutils::FileEqualityCheck::HardLink,
3858 )
3859 .await?;
3860 testutils::check_dirs_identical(
3862 &tmp_dir.join("update"),
3863 &tmp_dir.join("bar"),
3864 testutils::FileEqualityCheck::Timestamp,
3865 )
3866 .await?;
3867 Ok(())
3868 }
3869
3870 #[tokio::test]
3871 #[traced_test]
3872 async fn test_link_overwrite_hardlink_file() -> Result<(), anyhow::Error> {
3873 let tmp_dir = setup_test_dir_and_link().await?;
3874 let output_path = &tmp_dir.join("bar");
3875 {
3876 let bar_path = output_path.join("bar");
3885 let summary = rm::rm(
3886 &PROGRESS,
3887 &bar_path.join("1.txt"),
3888 &rm::Settings {
3889 fail_early: false,
3890 filter: None,
3891 dry_run: None,
3892 time_filter: None,
3893 },
3894 )
3895 .await?
3896 + rm::rm(
3897 &PROGRESS,
3898 &bar_path.join("2.txt"),
3899 &rm::Settings {
3900 fail_early: false,
3901 filter: None,
3902 dry_run: None,
3903 time_filter: None,
3904 },
3905 )
3906 .await?
3907 + rm::rm(
3908 &PROGRESS,
3909 &bar_path.join("3.txt"),
3910 &rm::Settings {
3911 fail_early: false,
3912 filter: None,
3913 dry_run: None,
3914 time_filter: None,
3915 },
3916 )
3917 .await?
3918 + rm::rm(
3919 &PROGRESS,
3920 &output_path.join("baz"),
3921 &rm::Settings {
3922 fail_early: false,
3923 filter: None,
3924 dry_run: None,
3925 time_filter: None,
3926 },
3927 )
3928 .await?;
3929 assert_eq!(summary.files_removed, 4);
3930 assert_eq!(summary.symlinks_removed, 2);
3931 assert_eq!(summary.directories_removed, 1);
3932 tokio::fs::write(bar_path.join("1.txt"), "1-new")
3934 .await
3935 .unwrap();
3936 tokio::fs::symlink("../0.txt", bar_path.join("2.txt"))
3937 .await
3938 .unwrap();
3939 tokio::fs::create_dir(&bar_path.join("3.txt"))
3940 .await
3941 .unwrap();
3942 tokio::fs::write(&output_path.join("baz"), "baz")
3943 .await
3944 .unwrap();
3945 }
3946 let summary = link(
3947 &PROGRESS,
3948 &tmp_dir,
3949 &tmp_dir.join("foo"),
3950 output_path,
3951 &None,
3952 &common_settings(false, true), false,
3954 )
3955 .await?;
3956 assert_eq!(summary.hard_links_created, 4);
3957 assert_eq!(summary.copy_summary.files_copied, 0);
3958 assert_eq!(summary.copy_summary.symlinks_created, 2);
3959 assert_eq!(summary.copy_summary.directories_created, 1);
3960 testutils::check_dirs_identical(
3961 &tmp_dir.join("foo"),
3962 &tmp_dir.join("bar"),
3963 testutils::FileEqualityCheck::HardLink,
3964 )
3965 .await?;
3966 Ok(())
3967 }
3968
3969 #[tokio::test]
3970 #[traced_test]
3971 async fn test_link_overwrite_error() -> Result<(), anyhow::Error> {
3972 let tmp_dir = setup_test_dir_and_link().await?;
3973 let output_path = &tmp_dir.join("bar");
3974 {
3975 let bar_path = output_path.join("bar");
3984 let summary = rm::rm(
3985 &PROGRESS,
3986 &bar_path.join("1.txt"),
3987 &rm::Settings {
3988 fail_early: false,
3989 filter: None,
3990 dry_run: None,
3991 time_filter: None,
3992 },
3993 )
3994 .await?
3995 + rm::rm(
3996 &PROGRESS,
3997 &bar_path.join("2.txt"),
3998 &rm::Settings {
3999 fail_early: false,
4000 filter: None,
4001 dry_run: None,
4002 time_filter: None,
4003 },
4004 )
4005 .await?
4006 + rm::rm(
4007 &PROGRESS,
4008 &bar_path.join("3.txt"),
4009 &rm::Settings {
4010 fail_early: false,
4011 filter: None,
4012 dry_run: None,
4013 time_filter: None,
4014 },
4015 )
4016 .await?
4017 + rm::rm(
4018 &PROGRESS,
4019 &output_path.join("baz"),
4020 &rm::Settings {
4021 fail_early: false,
4022 filter: None,
4023 dry_run: None,
4024 time_filter: None,
4025 },
4026 )
4027 .await?;
4028 assert_eq!(summary.files_removed, 4);
4029 assert_eq!(summary.symlinks_removed, 2);
4030 assert_eq!(summary.directories_removed, 1);
4031 tokio::fs::write(bar_path.join("1.txt"), "1-new")
4033 .await
4034 .unwrap();
4035 tokio::fs::symlink("../0.txt", bar_path.join("2.txt"))
4036 .await
4037 .unwrap();
4038 tokio::fs::create_dir(&bar_path.join("3.txt"))
4039 .await
4040 .unwrap();
4041 tokio::fs::write(&output_path.join("baz"), "baz")
4042 .await
4043 .unwrap();
4044 }
4045 let source_path = &tmp_dir.join("foo");
4046 tokio::fs::set_permissions(
4048 &source_path.join("baz"),
4049 std::fs::Permissions::from_mode(0o000),
4050 )
4051 .await?;
4052 match link(
4056 &PROGRESS,
4057 &tmp_dir,
4058 &tmp_dir.join("foo"),
4059 output_path,
4060 &None,
4061 &common_settings(false, true), false,
4063 )
4064 .await
4065 {
4066 Ok(_) => panic!("Expected the link to error!"),
4067 Err(error) => {
4068 tracing::info!("{:#}", &error);
4069 assert_eq!(error.summary.hard_links_created, 3);
4070 assert_eq!(error.summary.copy_summary.files_copied, 0);
4071 assert_eq!(error.summary.copy_summary.symlinks_created, 0);
4072 assert_eq!(error.summary.copy_summary.directories_created, 0);
4073 assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 1);
4074 assert_eq!(error.summary.copy_summary.rm_summary.directories_removed, 1);
4075 assert_eq!(error.summary.copy_summary.rm_summary.symlinks_removed, 1);
4076 }
4077 }
4078 Ok(())
4079 }
4080
4081 #[tokio::test]
4085 #[traced_test]
4086 async fn test_link_directory_metadata_applied_on_child_error() -> Result<(), anyhow::Error> {
4087 let tmp_dir = testutils::create_temp_dir().await?;
4088 let test_path = tmp_dir.as_path();
4089 let src_dir = test_path.join("src");
4091 tokio::fs::create_dir(&src_dir).await?;
4092 tokio::fs::set_permissions(&src_dir, std::fs::Permissions::from_mode(0o750)).await?;
4093 tokio::fs::write(src_dir.join("readable.txt"), "content").await?;
4095 let unreadable_subdir = src_dir.join("unreadable_subdir");
4098 tokio::fs::create_dir(&unreadable_subdir).await?;
4099 tokio::fs::write(unreadable_subdir.join("hidden.txt"), "secret").await?;
4100 tokio::fs::set_permissions(&unreadable_subdir, std::fs::Permissions::from_mode(0o000))
4101 .await?;
4102 let dst_dir = test_path.join("dst");
4103 let result = link(
4105 &PROGRESS,
4106 test_path,
4107 &src_dir,
4108 &dst_dir,
4109 &None,
4110 &common_settings(false, false),
4111 false,
4112 )
4113 .await;
4114 tokio::fs::set_permissions(&unreadable_subdir, std::fs::Permissions::from_mode(0o755))
4116 .await?;
4117 assert!(
4119 result.is_err(),
4120 "link should fail due to unreadable subdirectory"
4121 );
4122 let error = result.unwrap_err();
4123 assert_eq!(error.summary.hard_links_created, 1);
4125 let dst_metadata = tokio::fs::metadata(&dst_dir).await?;
4127 assert!(dst_metadata.is_dir());
4128 let actual_mode = dst_metadata.permissions().mode() & 0o7777;
4129 assert_eq!(
4130 actual_mode, 0o750,
4131 "directory should have preserved source permissions (0o750), got {:o}",
4132 actual_mode
4133 );
4134 Ok(())
4135 }
4136 mod filter_tests {
4137 use super::*;
4138 use crate::filter::FilterSettings;
4139
4140 async fn run_with_open_file_cleanup<F>(
4141 admission: &testutils::AdmissionLimit,
4142 operation: F,
4143 ) -> Result<F::Output, anyhow::Error>
4144 where
4145 F: std::future::Future,
4146 {
4147 let output = admission
4148 .run_with_timeout(std::time::Duration::from_secs(20), operation)
4149 .await
4150 .context("admission-sensitive filter operation did not finish")?;
4151 let permit = admission
4152 .run_with_timeout(
4153 std::time::Duration::from_secs(20),
4154 throttle::open_file_permit(),
4155 )
4156 .await
4157 .context("filter operation did not return open-file capacity")?;
4158 drop(permit);
4159 Ok(output)
4160 }
4161
4162 #[tokio::test]
4164 #[traced_test]
4165 async fn test_path_pattern_matches_nested_files() -> Result<(), anyhow::Error> {
4166 let tmp_dir = testutils::setup_test_dir().await?;
4167 let test_path = tmp_dir.as_path();
4168 let mut filter = FilterSettings::new();
4170 filter.add_include("bar/*.txt").unwrap();
4171 let summary = link(
4172 &PROGRESS,
4173 test_path,
4174 &test_path.join("foo"),
4175 &test_path.join("dst"),
4176 &None,
4177 &Settings {
4178 copy_settings: CopySettings {
4179 reflink: Default::default(),
4180 local_copy_handoff: Default::default(),
4181 dereference: false,
4182 fail_early: false,
4183 overwrite: false,
4184 overwrite_compare: Default::default(),
4185 overwrite_filter: None,
4186 ignore_existing: false,
4187 chunk_size: 0,
4188 skip_specials: false,
4189 remote_copy_buffer_size: 0,
4190 filter: None,
4191 dry_run: None,
4192 delete: None,
4193 },
4194 update_compare: Default::default(),
4195 update_exclusive: false,
4196 filter: Some(filter),
4197 dry_run: None,
4198 preserve: preserve::preserve_all(),
4199 },
4200 false,
4201 )
4202 .await?;
4203 assert_eq!(
4205 summary.hard_links_created, 3,
4206 "should link 3 files matching bar/*.txt"
4207 );
4208 assert!(
4210 test_path.join("dst/bar/1.txt").exists(),
4211 "bar/1.txt should be linked"
4212 );
4213 assert!(
4214 test_path.join("dst/bar/2.txt").exists(),
4215 "bar/2.txt should be linked"
4216 );
4217 assert!(
4218 test_path.join("dst/bar/3.txt").exists(),
4219 "bar/3.txt should be linked"
4220 );
4221 assert!(
4223 !test_path.join("dst/0.txt").exists(),
4224 "0.txt should not be linked"
4225 );
4226 Ok(())
4227 }
4228 #[tokio::test]
4233 #[traced_test]
4234 async fn test_filter_pruned_empty_dir_surfaces_child_error() -> Result<(), anyhow::Error> {
4235 let tmp_dir = testutils::create_temp_dir().await?;
4236 let test_path = tmp_dir.as_path();
4237 let src_dir = test_path.join("src");
4241 let unreadable = src_dir.join("sub").join("unreadable");
4242 tokio::fs::create_dir_all(&unreadable).await?;
4243 tokio::fs::write(unreadable.join("x.txt"), "secret").await?;
4244 tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).await?;
4245 let mut filter = FilterSettings::new();
4248 filter.add_include("*.match").unwrap();
4249 let mut settings = common_settings(false, false);
4250 settings.filter = Some(filter);
4251 let result = link(
4252 &PROGRESS,
4253 test_path,
4254 &src_dir,
4255 &test_path.join("dst"),
4256 &None,
4257 &settings,
4258 false,
4259 )
4260 .await;
4261 tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o755)).await?;
4263 assert!(
4264 result.is_err(),
4265 "a child link failure inside a filter-pruned empty directory must surface as an \
4266 error, not be masked as success"
4267 );
4268 Ok(())
4269 }
4270 #[tokio::test]
4273 #[traced_test]
4274 async fn test_filter_pruned_empty_dir_surfaces_child_error_dry_run()
4275 -> Result<(), anyhow::Error> {
4276 let tmp_dir = testutils::create_temp_dir().await?;
4277 let test_path = tmp_dir.as_path();
4278 let src_dir = test_path.join("src");
4279 let unreadable = src_dir.join("sub").join("unreadable");
4280 tokio::fs::create_dir_all(&unreadable).await?;
4281 tokio::fs::write(unreadable.join("x.txt"), "secret").await?;
4282 tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).await?;
4283 let mut filter = FilterSettings::new();
4284 filter.add_include("*.match").unwrap();
4285 let mut settings = common_settings(false, false);
4286 settings.filter = Some(filter);
4287 settings.dry_run = Some(crate::config::DryRunMode::Brief);
4288 settings.copy_settings.dry_run = Some(crate::config::DryRunMode::Brief);
4289 let result = link(
4290 &PROGRESS,
4291 test_path,
4292 &src_dir,
4293 &test_path.join("dst"),
4294 &None,
4295 &settings,
4296 false,
4297 )
4298 .await;
4299 tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o755)).await?;
4300 assert!(
4301 result.is_err(),
4302 "dry-run must also surface the child error, not report a clean run"
4303 );
4304 Ok(())
4305 }
4306 #[tokio::test]
4308 #[traced_test]
4309 async fn test_filter_applies_to_single_file_source() -> Result<(), anyhow::Error> {
4310 let tmp_dir = testutils::setup_test_dir().await?;
4311 let test_path = tmp_dir.as_path();
4312 let mut filter = FilterSettings::new();
4314 filter.add_exclude("*.txt").unwrap();
4315 let summary = link(
4316 &PROGRESS,
4317 test_path,
4318 &test_path.join("foo/0.txt"), &test_path.join("dst/0.txt"),
4320 &None,
4321 &Settings {
4322 copy_settings: CopySettings {
4323 reflink: Default::default(),
4324 local_copy_handoff: Default::default(),
4325 dereference: false,
4326 fail_early: false,
4327 overwrite: false,
4328 overwrite_compare: Default::default(),
4329 overwrite_filter: None,
4330 ignore_existing: false,
4331 chunk_size: 0,
4332 skip_specials: false,
4333 remote_copy_buffer_size: 0,
4334 filter: None,
4335 dry_run: None,
4336 delete: None,
4337 },
4338 update_compare: Default::default(),
4339 update_exclusive: false,
4340 filter: Some(filter),
4341 dry_run: None,
4342 preserve: preserve::preserve_all(),
4343 },
4344 false,
4345 )
4346 .await?;
4347 assert_eq!(
4349 summary.hard_links_created, 0,
4350 "file matching exclude pattern should not be linked"
4351 );
4352 assert!(
4353 !test_path.join("dst/0.txt").exists(),
4354 "excluded file should not exist at destination"
4355 );
4356 Ok(())
4357 }
4358 #[tokio::test]
4360 #[traced_test]
4361 async fn update_root_filter_uses_source_name_in_union_mode() -> Result<(), anyhow::Error> {
4362 let test_path = testutils::create_temp_dir().await?;
4363 let src = test_path.join("foo");
4364 let update = test_path.join("bar");
4365 let dst = test_path.join("dst");
4366 tokio::fs::write(&src, "SRC").await?;
4367 tokio::fs::write(&update, "UPDATED").await?;
4368 let mut filter = FilterSettings::new();
4369 filter.add_include("foo").unwrap();
4370 let mut settings = common_settings(false, false);
4371 settings.copy_settings.filter = Some(filter.clone());
4372 settings.filter = Some(filter);
4373 let summary = link(
4374 &PROGRESS,
4375 &test_path,
4376 &src,
4377 &dst,
4378 &Some(update),
4379 &settings,
4380 false,
4381 )
4382 .await?;
4383 assert_eq!(tokio::fs::read_to_string(&dst).await?, "UPDATED");
4384 assert_eq!(summary.copy_summary.files_copied, 1);
4385 Ok(())
4386 }
4387 #[tokio::test]
4389 #[traced_test]
4390 async fn update_root_filter_uses_source_name_in_exclusive_mode() -> Result<(), anyhow::Error>
4391 {
4392 let test_path = testutils::create_temp_dir().await?;
4393 let src = test_path.join("foo");
4394 let update = test_path.join("bar");
4395 let dst = test_path.join("dst");
4396 tokio::fs::write(&src, "SRC").await?;
4397 tokio::fs::write(&update, "UPDATED").await?;
4398 let mut filter = FilterSettings::new();
4399 filter.add_include("foo").unwrap();
4400 let mut settings = common_settings(false, false);
4401 settings.update_exclusive = true;
4402 settings.copy_settings.filter = Some(filter.clone());
4403 settings.filter = Some(filter);
4404 let summary = link(
4405 &PROGRESS,
4406 &test_path,
4407 &src,
4408 &dst,
4409 &Some(update),
4410 &settings,
4411 false,
4412 )
4413 .await?;
4414 assert_eq!(tokio::fs::read_to_string(&dst).await?, "UPDATED");
4415 assert_eq!(summary.copy_summary.files_copied, 1);
4416 Ok(())
4417 }
4418 #[tokio::test]
4420 #[traced_test]
4421 async fn update_directory_can_include_root_excluded_for_source_file()
4422 -> Result<(), anyhow::Error> {
4423 let test_path = testutils::create_temp_dir().await?;
4424 let src_parent = test_path.join("source");
4425 let update_parent = test_path.join("update");
4426 let src = src_parent.join("data");
4427 let update = update_parent.join("data");
4428 let dst = test_path.join("dst");
4429 tokio::fs::create_dir(&src_parent).await?;
4430 tokio::fs::create_dir(&update_parent).await?;
4431 tokio::fs::write(&src, "SOURCE-FILE").await?;
4432 tokio::fs::create_dir(&update).await?;
4433 tokio::fs::write(update.join("inner.txt"), "UPDATE-DIR").await?;
4434 let mut filter = FilterSettings::new();
4435 filter.add_include("data/").unwrap();
4436 filter.add_include("data/**").unwrap();
4437 let mut settings = common_settings(false, false);
4438 settings.filter = Some(filter);
4439 let summary = link(
4440 &PROGRESS,
4441 &test_path,
4442 &src,
4443 &dst,
4444 &Some(update),
4445 &settings,
4446 false,
4447 )
4448 .await?;
4449 assert_eq!(
4450 tokio::fs::read_to_string(dst.join("inner.txt")).await?,
4451 "UPDATE-DIR"
4452 );
4453 assert_eq!(summary.copy_summary.files_copied, 1);
4454 Ok(())
4455 }
4456 #[tokio::test]
4458 #[traced_test]
4459 async fn filtered_update_file_swap_to_directory_never_materializes_replacement()
4460 -> Result<(), anyhow::Error> {
4461 let test_path = testutils::create_temp_dir().await?;
4462 let src = test_path.join("src");
4463 let update = test_path.join("update");
4464 let dst = test_path.join("dst");
4465 tokio::fs::write(&src, "SRC").await?;
4466 tokio::fs::write(&update, "SELECTED-UPDATE-FILE").await?;
4467
4468 let admission_limits = testutils::AdmissionLimit::new().await;
4469 admission_limits.set_files_in_flight(1);
4470 let permit = walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
4471 let src_parent = Arc::new(
4472 Dir::open_parent_dir(&test_path, congestion::Side::Source)
4473 .await?
4474 .into_tree(),
4475 );
4476 let dst_parent = Arc::new(
4477 Dir::open_parent_dir(&test_path, congestion::Side::Destination)
4478 .await?
4479 .into_tree(),
4480 );
4481 let src_handle = src_parent.child(std::ffi::OsStr::new("src")).await?;
4482 let update_handle = src_parent.child(std::ffi::OsStr::new("update")).await?;
4483
4484 let mut filter = FilterSettings::new();
4485 filter.add_exclude("src/")?;
4486 assert!(matches!(
4487 select_filtered_root(
4488 &filter,
4489 std::ffi::OsStr::new("src"),
4490 src_handle.kind(),
4491 Some(update_handle.kind()),
4492 false,
4493 ),
4494 RootFilterSelection::WithUpdate
4495 ));
4496 let mut entry = AdmittedLinkEntry::new(src_handle, permit);
4497 entry.update_handle = Some(update_handle);
4498
4499 tokio::fs::remove_file(&update).await?;
4502 tokio::fs::create_dir(&update).await?;
4503 tokio::fs::write(update.join("replacement.txt"), "UNSELECTED").await?;
4504 let mut settings = common_settings(false, false);
4505 settings.filter = Some(filter);
4506
4507 let result = run_with_open_file_cleanup(
4508 &admission_limits,
4509 link_internal(
4510 &PROGRESS,
4511 &src_parent,
4512 Some((&src_parent, std::ffi::OsStr::new("update"))),
4513 Some(&dst_parent),
4514 std::ffi::OsStr::new("src"),
4515 &src,
4516 &dst,
4517 Some(&update),
4518 std::path::Path::new(""),
4519 UpdateRootRequirement::Optional,
4520 &settings,
4521 false,
4522 LinkEntryAdmission::Filtered(entry),
4523 copy::DestinationContext::new(&dst),
4524 ),
4525 )
4526 .await?;
4527
4528 assert!(
4529 result.is_err(),
4530 "a selected file reopened as a directory must fail closed"
4531 );
4532 assert!(
4533 !dst.exists(),
4534 "a failed-closed type swap must not create a destination"
4535 );
4536 Ok(())
4537 }
4538
4539 #[tokio::test]
4541 #[traced_test]
4542 async fn filtered_source_only_symlink_swap_to_directory_never_materializes_replacement()
4543 -> Result<(), anyhow::Error> {
4544 let test_path = testutils::create_temp_dir().await?;
4545 let src = test_path.join("src");
4546 let update = test_path.join("update");
4547 let dst = test_path.join("dst");
4548 tokio::fs::write(test_path.join("target"), "TARGET").await?;
4549 tokio::fs::symlink("target", &src).await?;
4550 tokio::fs::create_dir(&update).await?;
4551
4552 let admission_limits = testutils::AdmissionLimit::new().await;
4553 admission_limits.set_files_in_flight(1);
4554 let permit = walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
4555 let parent = Arc::new(
4556 Dir::open_parent_dir(&test_path, congestion::Side::Source)
4557 .await?
4558 .into_tree(),
4559 );
4560 let dst_parent = Arc::new(
4561 Dir::open_parent_dir(&test_path, congestion::Side::Destination)
4562 .await?
4563 .into_tree(),
4564 );
4565 let src_handle = parent.child(std::ffi::OsStr::new("src")).await?;
4566 let update_handle = parent.child(std::ffi::OsStr::new("update")).await?;
4567 let mut filter = FilterSettings::new();
4568 filter.add_exclude("src/")?;
4569 assert!(matches!(
4570 select_filtered_root(
4571 &filter,
4572 std::ffi::OsStr::new("src"),
4573 src_handle.kind(),
4574 Some(update_handle.kind()),
4575 false,
4576 ),
4577 RootFilterSelection::SourceOnly
4578 ));
4579 drop(update_handle);
4580 let entry = AdmittedLinkEntry::new(src_handle, permit);
4581
4582 tokio::fs::remove_file(&src).await?;
4585 tokio::fs::create_dir(&src).await?;
4586 tokio::fs::write(src.join("replacement.txt"), "UNSELECTED").await?;
4587 let mut settings = common_settings(false, false);
4588 settings.filter = Some(filter.clone());
4589 settings.copy_settings.filter = Some(filter);
4590
4591 run_with_open_file_cleanup(
4592 &admission_limits,
4593 link_internal(
4594 &PROGRESS,
4595 &parent,
4596 Some((&parent, std::ffi::OsStr::new("update"))),
4597 Some(&dst_parent),
4598 std::ffi::OsStr::new("src"),
4599 &src,
4600 &dst,
4601 Some(&update),
4602 std::path::Path::new(""),
4603 UpdateRootRequirement::Optional,
4604 &settings,
4605 false,
4606 LinkEntryAdmission::Filtered(entry),
4607 copy::DestinationContext::new(&dst),
4608 ),
4609 )
4610 .await??;
4611
4612 assert!(
4613 !dst.is_dir(),
4614 "the replacement directory passed the selected symlink's filter decision"
4615 );
4616 assert_eq!(
4617 tokio::fs::read_link(&dst).await?,
4618 std::path::Path::new("target")
4619 );
4620 Ok(())
4621 }
4622
4623 #[tokio::test]
4625 #[traced_test]
4626 async fn admitted_update_file_swap_to_file_copies_replacement_content()
4627 -> Result<(), anyhow::Error> {
4628 let test_path = testutils::create_temp_dir().await?;
4629 let src = test_path.join("src");
4630 let update = test_path.join("update");
4631 let dst = test_path.join("dst");
4632 tokio::fs::write(&src, "S").await?;
4633 tokio::fs::write(&update, "SELECTED-UPDATE").await?;
4634
4635 let admission_limits = testutils::AdmissionLimit::new().await;
4636 admission_limits.set_files_in_flight(1);
4637 let permit = walk::ensure_leaf_permit(PermitKind::OpenFile, None).await;
4638 let parent = Arc::new(
4639 Dir::open_parent_dir(&test_path, congestion::Side::Source)
4640 .await?
4641 .into_tree(),
4642 );
4643 let dst_parent = Arc::new(
4644 Dir::open_parent_dir(&test_path, congestion::Side::Destination)
4645 .await?
4646 .into_tree(),
4647 );
4648 let src_handle = parent.child(std::ffi::OsStr::new("src")).await?;
4649 let update_handle = parent.child(std::ffi::OsStr::new("update")).await?;
4650 let mut entry = AdmittedLinkEntry::new(src_handle, permit);
4651 entry.update_handle = Some(update_handle);
4652
4653 tokio::fs::remove_file(&update).await?;
4654 tokio::fs::write(&update, "REPLACEMENT-CONTENT").await?;
4655 run_with_open_file_cleanup(
4656 &admission_limits,
4657 link_internal(
4658 &PROGRESS,
4659 &parent,
4660 Some((&parent, std::ffi::OsStr::new("update"))),
4661 Some(&dst_parent),
4662 std::ffi::OsStr::new("src"),
4663 &src,
4664 &dst,
4665 Some(&update),
4666 std::path::Path::new(""),
4667 UpdateRootRequirement::Optional,
4668 &common_settings(false, false),
4669 false,
4670 LinkEntryAdmission::Filtered(entry),
4671 copy::DestinationContext::new(&dst),
4672 ),
4673 )
4674 .await??;
4675
4676 assert_eq!(
4677 tokio::fs::read_to_string(&dst).await?,
4678 "REPLACEMENT-CONTENT"
4679 );
4680 Ok(())
4681 }
4682
4683 #[tokio::test]
4685 #[traced_test]
4686 async fn update_only_unknown_file_swap_to_excluded_directory_never_materializes_replacement()
4687 -> Result<(), anyhow::Error> {
4688 let test_path = testutils::create_temp_dir().await?;
4689 let update = test_path.join("update");
4690 let dst = test_path.join("dst");
4691 let admission_limits = testutils::AdmissionLimit::new().await;
4692 admission_limits.set_files_in_flight(1);
4693 tokio::fs::create_dir(&update).await?;
4694 tokio::fs::create_dir(&dst).await?;
4695 let entry_path = update.join("node");
4696 let dst_path = dst.join("node");
4697 tokio::fs::write(&entry_path, "SELECTED-UPDATE-FILE").await?;
4698 let update_parent =
4699 Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
4700 let dst_parent =
4701 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
4702 let mut filter = FilterSettings::new();
4703 filter.add_exclude("node/")?;
4704 let mut settings = common_settings(false, false);
4705 settings.filter = Some(filter.clone());
4706 settings.copy_settings.filter = Some(filter);
4707 let admission =
4708 walk::ensure_entry_admission(PermitKind::OpenFile, EntryAdmission::RootOrDelegated)
4709 .await;
4710 let selected = select_exact_update_only_for_dispatch(
4711 &update_parent,
4712 std::ffi::OsStr::new("node"),
4713 admission,
4714 std::path::Path::new("node"),
4715 settings.filter.as_ref(),
4716 )
4717 .await?;
4718 let UpdateOnlyDecision::Admitted(entry) = selected else {
4719 panic!("the forced-unknown file must pass the non-directory filter")
4720 };
4721 assert_eq!(entry.kind(), EntryKind::File);
4722
4723 tokio::fs::remove_file(&entry_path).await?;
4724 tokio::fs::create_dir(&entry_path).await?;
4725 tokio::fs::write(entry_path.join("replacement.txt"), "UNSELECTED").await?;
4726 let result = run_with_open_file_cleanup(
4727 &admission_limits,
4728 delegate_copy(
4729 &PROGRESS,
4730 &update_parent,
4731 Some(&dst_parent),
4732 std::ffi::OsStr::new("node"),
4733 &entry_path,
4734 &dst,
4735 std::path::Path::new("node"),
4736 copy::DestinationContext::parent(Some(Arc::clone(&dst_parent))),
4737 &settings,
4738 false,
4739 entry,
4740 ),
4741 )
4742 .await?;
4743
4744 assert!(
4745 result.is_err(),
4746 "a selected file reopened as a directory must fail closed"
4747 );
4748 assert!(
4749 !dst_path.exists(),
4750 "a failed-closed type swap must not create a destination"
4751 );
4752 Ok(())
4753 }
4754
4755 #[tokio::test]
4757 #[traced_test]
4758 async fn nested_source_unknown_file_swap_to_excluded_directory_is_rechecked()
4759 -> Result<(), anyhow::Error> {
4760 let test_path = testutils::create_temp_dir().await?;
4761 let src = test_path.join("src");
4762 let dst = test_path.join("dst");
4763 tokio::fs::create_dir(&src).await?;
4764 tokio::fs::create_dir(&dst).await?;
4765 let entry_path = src.join("node");
4766 tokio::fs::write(&entry_path, "SELECTED-FILE").await?;
4767 tokio::fs::write(dst.join("node"), "STALE-DESTINATION").await?;
4768 let src_parent =
4769 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
4770 let dst_parent =
4771 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
4772 let mut filter = FilterSettings::new();
4773 filter.add_exclude("node/")?;
4774 let initially_is_dir = walk::filter_is_dir(
4775 Some(&filter),
4776 &src_parent,
4777 std::ffi::OsStr::new("node"),
4778 None,
4779 false,
4780 )
4781 .await?;
4782 assert!(!initially_is_dir);
4783 assert!(
4784 walk::should_skip_entry(&Some(filter.clone()), std::path::Path::new("node"), false)
4785 .is_none()
4786 );
4787
4788 tokio::fs::remove_file(&entry_path).await?;
4789 tokio::fs::create_dir(&entry_path).await?;
4790 tokio::fs::write(entry_path.join("replacement.txt"), "UNSELECTED").await?;
4791 let mut settings = common_settings(false, false);
4792 settings.filter = Some(filter.clone());
4793 settings.copy_settings.filter = Some(filter);
4794 let delete_settings = copy::DeleteSettings {
4795 delete_excluded: true,
4796 };
4797 let mut outcomes = LinkChildOutcomes::new(Some(&delete_settings));
4798 let result = crate::task_scope::scope_tasks(link_internal(
4799 &PROGRESS,
4800 &src_parent,
4801 None,
4802 Some(&dst_parent),
4803 std::ffi::OsStr::new("node"),
4804 &src,
4805 &dst,
4806 None,
4807 std::path::Path::new("node"),
4808 UpdateRootRequirement::Optional,
4809 &settings,
4810 false,
4811 EntryAdmission::RootOrDelegated.into(),
4812 copy::DestinationContext::parent(Some(Arc::clone(&dst_parent))),
4813 ))
4814 .await?;
4815 let mut summary = Summary::default();
4816 LinkTaskResult::from_link(std::ffi::OsString::from("node"), result)
4817 .fold(&mut summary, &mut outcomes);
4818 crate::delete::prune_and_fold(
4819 &PROGRESS,
4820 &dst_parent,
4821 crate::delete::DeleteSources::Single(&src_parent),
4822 std::path::Path::new(""),
4823 &outcomes.expect_ready(),
4824 settings.filter.as_ref(),
4825 false,
4826 None,
4827 &mut summary.copy_summary.rm_summary,
4828 None,
4829 )
4830 .await?;
4831
4832 assert!(
4833 !dst.join("node").exists(),
4834 "the exact filtered result did not remove the stale outer keep decision"
4835 );
4836 assert_eq!(summary.copy_summary.directories_skipped, 1);
4837 Ok(())
4838 }
4839
4840 #[tokio::test]
4843 #[traced_test]
4844 async fn destructive_source_stale_directory_hint_rechecks_included_file()
4845 -> Result<(), anyhow::Error> {
4846 let test_path = testutils::create_temp_dir().await?;
4847 let src = test_path.join("src");
4848 let dst = test_path.join("dst");
4849 tokio::fs::create_dir(&src).await?;
4850 tokio::fs::create_dir(&dst).await?;
4851 tokio::fs::write(src.join("node"), "CURRENT-SOURCE").await?;
4852 tokio::fs::write(dst.join("node"), "STALE-DESTINATION").await?;
4853 let src_dir =
4854 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
4855 let dst_dir =
4856 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
4857
4858 let mut filter = FilterSettings::new();
4859 filter.add_exclude("node/")?;
4860 let delete_settings = copy::DeleteSettings {
4861 delete_excluded: false,
4862 };
4863 let mut settings = common_settings(false, true);
4864 settings.filter = Some(filter.clone());
4865 settings.copy_settings.filter = Some(filter);
4866 settings.copy_settings.delete = Some(delete_settings.clone());
4867 let decision = select_source_for_dispatch(
4868 Some(EntryKind::Dir),
4869 std::path::Path::new("node"),
4870 &settings,
4871 false,
4872 );
4873
4874 let mut summary = Summary::default();
4875 let mut outcomes = LinkChildOutcomes::new(Some(&delete_settings));
4876 match decision {
4877 SourceEntryDecision::Filtered { kind, .. } => {
4878 summary = summary + skipped_summary_for(kind);
4879 }
4880 SourceEntryDecision::Dispatch(admission) => {
4881 let admission =
4882 walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
4883 let result = crate::task_scope::scope_tasks(link_internal(
4884 &PROGRESS,
4885 &src_dir,
4886 None,
4887 Some(&dst_dir),
4888 std::ffi::OsStr::new("node"),
4889 &src,
4890 &dst,
4891 None,
4892 std::path::Path::new("node"),
4893 UpdateRootRequirement::Optional,
4894 &settings,
4895 false,
4896 admission.into(),
4897 copy::DestinationContext::parent(Some(Arc::clone(&dst_dir))),
4898 ))
4899 .await?;
4900 LinkTaskResult::from_link(std::ffi::OsString::from("node"), result)
4901 .fold(&mut summary, &mut outcomes);
4902 }
4903 }
4904 crate::delete::prune_and_fold(
4905 &PROGRESS,
4906 &dst_dir,
4907 crate::delete::DeleteSources::Single(&src_dir),
4908 std::path::Path::new(""),
4909 &outcomes.expect_ready(),
4910 settings.filter.as_ref(),
4911 false,
4912 None,
4913 &mut summary.copy_summary.rm_summary,
4914 None,
4915 )
4916 .await?;
4917
4918 assert_eq!(
4919 tokio::fs::read_to_string(dst.join("node")).await?,
4920 "CURRENT-SOURCE",
4921 "the exact included file must materialize and protect its destination name"
4922 );
4923 assert_eq!(summary.hard_links_created, 1);
4924 Ok(())
4925 }
4926
4927 #[tokio::test]
4930 #[traced_test]
4931 async fn dry_run_source_stale_directory_hint_reports_included_file()
4932 -> Result<(), anyhow::Error> {
4933 let test_path = testutils::create_temp_dir().await?;
4934 let src = test_path.join("src");
4935 let dst = test_path.join("dst");
4936 tokio::fs::create_dir(&src).await?;
4937 tokio::fs::write(src.join("node"), "CURRENT-SOURCE").await?;
4938 let src_dir =
4939 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
4940
4941 let mut filter = FilterSettings::new();
4942 filter.add_exclude("node/")?;
4943 let mut settings = common_settings(false, false);
4944 settings.filter = Some(filter.clone());
4945 settings.copy_settings.filter = Some(filter);
4946 settings.dry_run = Some(crate::config::DryRunMode::Brief);
4947 let decision = select_source_for_dispatch(
4948 Some(EntryKind::Dir),
4949 std::path::Path::new("node"),
4950 &settings,
4951 false,
4952 );
4953
4954 let mut summary = Summary::default();
4955 let mut outcomes = LinkChildOutcomes::new(None);
4956 match decision {
4957 SourceEntryDecision::Filtered { kind, .. } => {
4958 summary = summary + skipped_summary_for(kind);
4959 }
4960 SourceEntryDecision::Dispatch(admission) => {
4961 let admission =
4962 walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
4963 let result = crate::task_scope::scope_tasks(link_internal(
4964 &PROGRESS,
4965 &src_dir,
4966 None,
4967 None,
4968 std::ffi::OsStr::new("node"),
4969 &src,
4970 &dst,
4971 None,
4972 std::path::Path::new("node"),
4973 UpdateRootRequirement::Optional,
4974 &settings,
4975 false,
4976 admission.into(),
4977 copy::DestinationContext::parent(None),
4978 ))
4979 .await?;
4980 LinkTaskResult::from_link(std::ffi::OsString::from("node"), result)
4981 .fold(&mut summary, &mut outcomes);
4982 }
4983 }
4984
4985 assert_eq!(summary.hard_links_created, 1);
4986 assert_eq!(summary.copy_summary.directories_skipped, 0);
4987 assert!(!dst.join("node").exists());
4988 Ok(())
4989 }
4990
4991 #[tokio::test]
4994 #[traced_test]
4995 async fn skip_specials_stale_special_hint_rechecks_regular_file()
4996 -> Result<(), anyhow::Error> {
4997 let test_path = testutils::create_temp_dir().await?;
4998 let src = test_path.join("src");
4999 let dst = test_path.join("dst");
5000 tokio::fs::create_dir(&src).await?;
5001 tokio::fs::create_dir(&dst).await?;
5002 tokio::fs::write(src.join("node"), "CURRENT-SOURCE").await?;
5003 tokio::fs::write(dst.join("node"), "STALE-DESTINATION").await?;
5004 let src_dir =
5005 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
5006 let dst_dir =
5007 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
5008
5009 let delete_settings = copy::DeleteSettings {
5010 delete_excluded: false,
5011 };
5012 let mut settings = common_settings(false, true);
5013 settings.copy_settings.skip_specials = true;
5014 settings.copy_settings.delete = Some(delete_settings.clone());
5015 let decision = select_source_for_dispatch(
5016 Some(EntryKind::Special),
5017 std::path::Path::new("node"),
5018 &settings,
5019 false,
5020 );
5021
5022 let mut summary = Summary::default();
5023 let mut outcomes = LinkChildOutcomes::new(Some(&delete_settings));
5024 match decision {
5025 SourceEntryDecision::Filtered { kind, .. } => {
5026 summary = summary + skipped_summary_for(kind);
5027 }
5028 SourceEntryDecision::Dispatch(admission) => {
5029 let admission =
5030 walk::ensure_entry_admission(PermitKind::OpenFile, admission).await;
5031 let result = crate::task_scope::scope_tasks(link_internal(
5032 &PROGRESS,
5033 &src_dir,
5034 None,
5035 Some(&dst_dir),
5036 std::ffi::OsStr::new("node"),
5037 &src,
5038 &dst,
5039 None,
5040 std::path::Path::new("node"),
5041 UpdateRootRequirement::Optional,
5042 &settings,
5043 false,
5044 admission.into(),
5045 copy::DestinationContext::parent(Some(Arc::clone(&dst_dir))),
5046 ))
5047 .await?;
5048 LinkTaskResult::from_link(std::ffi::OsString::from("node"), result)
5049 .fold(&mut summary, &mut outcomes);
5050 }
5051 }
5052 crate::delete::prune_and_fold(
5053 &PROGRESS,
5054 &dst_dir,
5055 crate::delete::DeleteSources::Single(&src_dir),
5056 std::path::Path::new(""),
5057 &outcomes.expect_ready(),
5058 None,
5059 false,
5060 None,
5061 &mut summary.copy_summary.rm_summary,
5062 None,
5063 )
5064 .await?;
5065
5066 assert_eq!(
5067 tokio::fs::read_to_string(dst.join("node")).await?,
5068 "CURRENT-SOURCE",
5069 "the exact regular file must replace stale destination content"
5070 );
5071 assert_eq!(summary.hard_links_created, 1);
5072 assert_eq!(summary.copy_summary.specials_skipped, 0);
5073 Ok(())
5074 }
5075
5076 #[tokio::test]
5079 #[traced_test]
5080 async fn destructive_update_stale_directory_hint_rechecks_included_file()
5081 -> Result<(), anyhow::Error> {
5082 let test_path = testutils::create_temp_dir().await?;
5083 let update = test_path.join("update");
5084 let dst = test_path.join("dst");
5085 tokio::fs::create_dir(&update).await?;
5086 tokio::fs::create_dir(&dst).await?;
5087 tokio::fs::write(update.join("node"), "CURRENT-UPDATE").await?;
5088 tokio::fs::write(dst.join("node"), "STALE-DESTINATION").await?;
5089 let update_dir =
5090 Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
5091 let dst_dir =
5092 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
5093
5094 let mut filter = FilterSettings::new();
5095 filter.add_exclude("node/")?;
5096 let delete_settings = copy::DeleteSettings {
5097 delete_excluded: false,
5098 };
5099 let mut settings = common_settings(false, true);
5100 settings.filter = Some(filter.clone());
5101 settings.copy_settings.filter = Some(filter);
5102 settings.copy_settings.delete = Some(delete_settings.clone());
5103 let decision = select_exact_update_only_for_dispatch(
5104 &update_dir,
5105 std::ffi::OsStr::new("node"),
5106 EntryAdmission::HintedDirectory,
5107 std::path::Path::new("node"),
5108 settings.filter.as_ref(),
5109 )
5110 .await?;
5111
5112 let mut summary = Summary::default();
5113 let mut outcomes = LinkChildOutcomes::new(Some(&delete_settings));
5114 match decision {
5115 UpdateOnlyDecision::Skipped { kind, .. } => {
5116 summary = summary + skipped_summary_for(kind);
5117 }
5118 UpdateOnlyDecision::Admitted(entry) => {
5119 let result = delegate_copy(
5120 &PROGRESS,
5121 &update_dir,
5122 Some(&dst_dir),
5123 std::ffi::OsStr::new("node"),
5124 &update.join("node"),
5125 &dst,
5126 std::path::Path::new("node"),
5127 copy::DestinationContext::parent(Some(Arc::clone(&dst_dir))),
5128 &settings,
5129 false,
5130 entry,
5131 )
5132 .await?;
5133 LinkTaskResult::from_update(
5134 std::ffi::OsString::from("node"),
5135 LinkEntryResult::selected(result),
5136 )
5137 .fold(&mut summary, &mut outcomes);
5138 }
5139 }
5140 crate::delete::prune_and_fold(
5141 &PROGRESS,
5142 &dst_dir,
5143 crate::delete::DeleteSources::Single(&update_dir),
5144 std::path::Path::new(""),
5145 &outcomes.expect_ready(),
5146 settings.filter.as_ref(),
5147 false,
5148 None,
5149 &mut summary.copy_summary.rm_summary,
5150 None,
5151 )
5152 .await?;
5153
5154 assert_eq!(
5155 tokio::fs::read_to_string(dst.join("node")).await?,
5156 "CURRENT-UPDATE",
5157 "the exact included update file must materialize and protect its destination name"
5158 );
5159 assert_eq!(summary.copy_summary.files_copied, 1);
5160 Ok(())
5161 }
5162
5163 #[tokio::test]
5165 #[traced_test]
5166 async fn dry_run_update_stale_directory_hint_reports_included_file()
5167 -> Result<(), anyhow::Error> {
5168 let test_path = testutils::create_temp_dir().await?;
5169 let update = test_path.join("update");
5170 let dst = test_path.join("dst");
5171 tokio::fs::create_dir(&update).await?;
5172 tokio::fs::write(update.join("node"), "CURRENT-UPDATE").await?;
5173 let update_dir =
5174 Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
5175
5176 let mut filter = FilterSettings::new();
5177 filter.add_exclude("node/")?;
5178 let mut settings = common_settings(false, false);
5179 settings.filter = Some(filter.clone());
5180 settings.copy_settings.filter = Some(filter);
5181 settings.dry_run = Some(crate::config::DryRunMode::Brief);
5182 let decision = select_exact_update_only_for_dispatch(
5183 &update_dir,
5184 std::ffi::OsStr::new("node"),
5185 EntryAdmission::HintedDirectory,
5186 std::path::Path::new("node"),
5187 settings.filter.as_ref(),
5188 )
5189 .await?;
5190
5191 let mut summary = Summary::default();
5192 let mut outcomes = LinkChildOutcomes::new(None);
5193 match decision {
5194 UpdateOnlyDecision::Skipped { kind, .. } => {
5195 summary = summary + skipped_summary_for(kind);
5196 }
5197 UpdateOnlyDecision::Admitted(entry) => {
5198 let result = delegate_copy(
5199 &PROGRESS,
5200 &update_dir,
5201 None,
5202 std::ffi::OsStr::new("node"),
5203 &update.join("node"),
5204 &dst,
5205 std::path::Path::new("node"),
5206 copy::DestinationContext::parent(None),
5207 &settings,
5208 false,
5209 entry,
5210 )
5211 .await?;
5212 LinkTaskResult::from_update(
5213 std::ffi::OsString::from("node"),
5214 LinkEntryResult::selected(result),
5215 )
5216 .fold(&mut summary, &mut outcomes);
5217 }
5218 }
5219
5220 assert_eq!(summary.copy_summary.files_copied, 1);
5221 assert_eq!(summary.copy_summary.directories_skipped, 0);
5222 assert!(!dst.join("node").exists());
5223 Ok(())
5224 }
5225
5226 #[tokio::test]
5228 #[traced_test]
5229 async fn excluded_dual_root_skips_before_destination_validation()
5230 -> Result<(), anyhow::Error> {
5231 let test_path = testutils::create_temp_dir().await?;
5232 let src_parent = test_path.join("source");
5233 let update_parent = test_path.join("update");
5234 let src = src_parent.join("blocked");
5235 let update = update_parent.join("blocked");
5236 tokio::fs::create_dir(&src_parent).await?;
5237 tokio::fs::create_dir(&update_parent).await?;
5238 tokio::fs::write(&src, "SRC").await?;
5239 tokio::fs::write(&update, "UPDATE").await?;
5240 let mut filter = FilterSettings::new();
5241 filter.add_exclude("blocked").unwrap();
5242 let mut settings = common_settings(false, false);
5243 settings.filter = Some(filter);
5244 let summary = link(
5245 &PROGRESS,
5246 &test_path,
5247 &src,
5248 std::path::Path::new("/"),
5249 &Some(update),
5250 &settings,
5251 false,
5252 )
5253 .await?;
5254 assert_eq!(summary.copy_summary.files_skipped, 1);
5255 Ok(())
5256 }
5257
5258 #[tokio::test]
5261 async fn excluded_source_only_root_skips_under_execute_only_parent()
5262 -> Result<(), anyhow::Error> {
5263 let test_path = testutils::create_temp_dir().await?;
5264 let parent = test_path.join("parent");
5265 let src = parent.join("src");
5266 let dst = test_path.join("dst");
5267 tokio::fs::create_dir_all(&src).await?;
5268 tokio::fs::write(src.join("leaf"), b"leaf").await?;
5269 let mut filter = FilterSettings::new();
5270 filter.add_exclude("src")?;
5271 let mut settings = common_settings(false, false);
5272 settings.filter = Some(filter.clone());
5273 settings.copy_settings.filter = Some(filter);
5274 tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o111)).await?;
5275 let result = link(&PROGRESS, &test_path, &src, &dst, &None, &settings, false).await;
5276 tokio::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o755)).await?;
5277 let summary = result?;
5278 assert_eq!(summary.copy_summary.directories_skipped, 1);
5279 assert!(!dst.exists());
5280 Ok(())
5281 }
5282
5283 #[tokio::test]
5285 #[traced_test]
5286 async fn test_filter_applies_to_root_directory() -> Result<(), anyhow::Error> {
5287 let test_path = testutils::create_temp_dir().await?;
5288 tokio::fs::create_dir_all(test_path.join("excluded_dir")).await?;
5290 tokio::fs::write(test_path.join("excluded_dir/file.txt"), "content").await?;
5291 let mut filter = FilterSettings::new();
5293 filter.add_exclude("*_dir/").unwrap();
5294 let result = link(
5295 &PROGRESS,
5296 &test_path,
5297 &test_path.join("excluded_dir"),
5298 &test_path.join("dst"),
5299 &None,
5300 &Settings {
5301 copy_settings: CopySettings {
5302 reflink: Default::default(),
5303 local_copy_handoff: Default::default(),
5304 dereference: false,
5305 fail_early: false,
5306 overwrite: false,
5307 overwrite_compare: Default::default(),
5308 overwrite_filter: None,
5309 ignore_existing: false,
5310 chunk_size: 0,
5311 skip_specials: false,
5312 remote_copy_buffer_size: 0,
5313 filter: None,
5314 dry_run: None,
5315 delete: None,
5316 },
5317 update_compare: Default::default(),
5318 update_exclusive: false,
5319 filter: Some(filter),
5320 dry_run: None,
5321 preserve: preserve::preserve_all(),
5322 },
5323 false,
5324 )
5325 .await?;
5326 assert_eq!(
5328 result.copy_summary.directories_created, 0,
5329 "root directory matching exclude should not be created"
5330 );
5331 assert!(
5332 !test_path.join("dst").exists(),
5333 "excluded root directory should not exist at destination"
5334 );
5335 Ok(())
5336 }
5337 #[tokio::test]
5339 #[traced_test]
5340 async fn test_filter_applies_to_root_symlink() -> Result<(), anyhow::Error> {
5341 let test_path = testutils::create_temp_dir().await?;
5342 tokio::fs::write(test_path.join("target.txt"), "content").await?;
5344 tokio::fs::symlink(
5345 test_path.join("target.txt"),
5346 test_path.join("excluded_link"),
5347 )
5348 .await?;
5349 let mut filter = FilterSettings::new();
5351 filter.add_exclude("*_link").unwrap();
5352 let result = link(
5353 &PROGRESS,
5354 &test_path,
5355 &test_path.join("excluded_link"),
5356 &test_path.join("dst"),
5357 &None,
5358 &Settings {
5359 copy_settings: CopySettings {
5360 reflink: Default::default(),
5361 local_copy_handoff: Default::default(),
5362 dereference: false,
5363 fail_early: false,
5364 overwrite: false,
5365 overwrite_compare: Default::default(),
5366 overwrite_filter: None,
5367 ignore_existing: false,
5368 chunk_size: 0,
5369 skip_specials: false,
5370 remote_copy_buffer_size: 0,
5371 filter: None,
5372 dry_run: None,
5373 delete: None,
5374 },
5375 update_compare: Default::default(),
5376 update_exclusive: false,
5377 filter: Some(filter),
5378 dry_run: None,
5379 preserve: preserve::preserve_all(),
5380 },
5381 false,
5382 )
5383 .await?;
5384 assert_eq!(
5386 result.copy_summary.symlinks_created, 0,
5387 "root symlink matching exclude should not be created"
5388 );
5389 assert!(
5390 !test_path.join("dst").exists(),
5391 "excluded root symlink should not exist at destination"
5392 );
5393 Ok(())
5394 }
5395 #[tokio::test]
5397 #[traced_test]
5398 async fn test_combined_include_exclude_patterns() -> Result<(), anyhow::Error> {
5399 let tmp_dir = testutils::setup_test_dir().await?;
5400 let test_path = tmp_dir.as_path();
5401 let mut filter = FilterSettings::new();
5408 filter.add_include("bar/*.txt").unwrap();
5409 filter.add_exclude("bar/2.txt").unwrap();
5410 let summary = link(
5411 &PROGRESS,
5412 test_path,
5413 &test_path.join("foo"),
5414 &test_path.join("dst"),
5415 &None,
5416 &Settings {
5417 copy_settings: CopySettings {
5418 reflink: Default::default(),
5419 local_copy_handoff: Default::default(),
5420 dereference: false,
5421 fail_early: false,
5422 overwrite: false,
5423 overwrite_compare: Default::default(),
5424 overwrite_filter: None,
5425 ignore_existing: false,
5426 chunk_size: 0,
5427 skip_specials: false,
5428 remote_copy_buffer_size: 0,
5429 filter: None,
5430 dry_run: None,
5431 delete: None,
5432 },
5433 update_compare: Default::default(),
5434 update_exclusive: false,
5435 filter: Some(filter),
5436 dry_run: None,
5437 preserve: preserve::preserve_all(),
5438 },
5439 false,
5440 )
5441 .await?;
5442 assert_eq!(summary.hard_links_created, 2, "should create 2 hard links");
5445 assert_eq!(
5446 summary.copy_summary.files_skipped, 2,
5447 "should skip 2 files (bar/2.txt excluded, 0.txt no match)"
5448 );
5449 assert!(
5451 test_path.join("dst/bar/1.txt").exists(),
5452 "bar/1.txt should be linked"
5453 );
5454 assert!(
5455 !test_path.join("dst/bar/2.txt").exists(),
5456 "bar/2.txt should be excluded"
5457 );
5458 assert!(
5459 test_path.join("dst/bar/3.txt").exists(),
5460 "bar/3.txt should be linked"
5461 );
5462 Ok(())
5463 }
5464 #[tokio::test]
5466 #[traced_test]
5467 async fn test_skipped_counts_comprehensive() -> Result<(), anyhow::Error> {
5468 let tmp_dir = testutils::setup_test_dir().await?;
5469 let test_path = tmp_dir.as_path();
5470 let mut filter = FilterSettings::new();
5477 filter.add_exclude("bar/").unwrap();
5478 let summary = link(
5479 &PROGRESS,
5480 test_path,
5481 &test_path.join("foo"),
5482 &test_path.join("dst"),
5483 &None,
5484 &Settings {
5485 copy_settings: CopySettings {
5486 reflink: Default::default(),
5487 local_copy_handoff: Default::default(),
5488 dereference: false,
5489 fail_early: false,
5490 overwrite: false,
5491 overwrite_compare: Default::default(),
5492 overwrite_filter: None,
5493 ignore_existing: false,
5494 chunk_size: 0,
5495 skip_specials: false,
5496 remote_copy_buffer_size: 0,
5497 filter: None,
5498 dry_run: None,
5499 delete: None,
5500 },
5501 update_compare: Default::default(),
5502 update_exclusive: false,
5503 filter: Some(filter),
5504 dry_run: None,
5505 preserve: preserve::preserve_all(),
5506 },
5507 false,
5508 )
5509 .await?;
5510 assert_eq!(summary.hard_links_created, 2, "should create 2 hard links");
5514 assert_eq!(
5515 summary.copy_summary.symlinks_created, 2,
5516 "should copy 2 symlinks"
5517 );
5518 assert_eq!(
5519 summary.copy_summary.directories_skipped, 1,
5520 "should skip 1 directory (bar)"
5521 );
5522 assert!(
5524 !test_path.join("dst/bar").exists(),
5525 "bar directory should not be linked"
5526 );
5527 Ok(())
5528 }
5529 #[tokio::test]
5532 #[traced_test]
5533 async fn test_empty_dir_not_created_when_only_traversed() -> Result<(), anyhow::Error> {
5534 let test_path = testutils::create_temp_dir().await?;
5535 let src_path = test_path.join("src");
5541 tokio::fs::create_dir(&src_path).await?;
5542 tokio::fs::write(src_path.join("foo"), "content").await?;
5543 tokio::fs::write(src_path.join("bar"), "content").await?;
5544 tokio::fs::create_dir(src_path.join("baz")).await?;
5545 let mut filter = FilterSettings::new();
5547 filter.add_include("foo").unwrap();
5548 let summary = link(
5549 &PROGRESS,
5550 &test_path,
5551 &src_path,
5552 &test_path.join("dst"),
5553 &None,
5554 &Settings {
5555 copy_settings: copy::Settings {
5556 reflink: Default::default(),
5557 local_copy_handoff: Default::default(),
5558 dereference: false,
5559 fail_early: false,
5560 overwrite: false,
5561 overwrite_compare: Default::default(),
5562 overwrite_filter: None,
5563 ignore_existing: false,
5564 chunk_size: 0,
5565 skip_specials: false,
5566 remote_copy_buffer_size: 0,
5567 filter: None,
5568 dry_run: None,
5569 delete: None,
5570 },
5571 update_compare: Default::default(),
5572 update_exclusive: false,
5573 filter: Some(filter),
5574 dry_run: None,
5575 preserve: preserve::preserve_all(),
5576 },
5577 false,
5578 )
5579 .await?;
5580 assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
5582 assert_eq!(
5583 summary.copy_summary.directories_created, 1,
5584 "should create only root directory (not empty 'baz')"
5585 );
5586 assert!(
5588 test_path.join("dst").join("foo").exists(),
5589 "foo should be linked"
5590 );
5591 assert!(
5593 !test_path.join("dst").join("bar").exists(),
5594 "bar should not be linked"
5595 );
5596 assert!(
5598 !test_path.join("dst").join("baz").exists(),
5599 "empty baz directory should NOT be created"
5600 );
5601 Ok(())
5602 }
5603 #[tokio::test]
5606 #[traced_test]
5607 async fn test_dir_with_nonmatching_content_not_created() -> Result<(), anyhow::Error> {
5608 let test_path = testutils::create_temp_dir().await?;
5609 let src_path = test_path.join("src");
5616 tokio::fs::create_dir(&src_path).await?;
5617 tokio::fs::write(src_path.join("foo"), "content").await?;
5618 tokio::fs::create_dir(src_path.join("baz")).await?;
5619 tokio::fs::write(src_path.join("baz").join("qux"), "content").await?;
5620 tokio::fs::write(src_path.join("baz").join("quux"), "content").await?;
5621 let mut filter = FilterSettings::new();
5623 filter.add_include("foo").unwrap();
5624 let summary = link(
5625 &PROGRESS,
5626 &test_path,
5627 &src_path,
5628 &test_path.join("dst"),
5629 &None,
5630 &Settings {
5631 copy_settings: copy::Settings {
5632 reflink: Default::default(),
5633 local_copy_handoff: Default::default(),
5634 dereference: false,
5635 fail_early: false,
5636 overwrite: false,
5637 overwrite_compare: Default::default(),
5638 overwrite_filter: None,
5639 ignore_existing: false,
5640 chunk_size: 0,
5641 skip_specials: false,
5642 remote_copy_buffer_size: 0,
5643 filter: None,
5644 dry_run: None,
5645 delete: None,
5646 },
5647 update_compare: Default::default(),
5648 update_exclusive: false,
5649 filter: Some(filter),
5650 dry_run: None,
5651 preserve: preserve::preserve_all(),
5652 },
5653 false,
5654 )
5655 .await?;
5656 assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
5658 assert_eq!(
5659 summary.copy_summary.files_skipped, 2,
5660 "should skip 2 files (qux and quux)"
5661 );
5662 assert_eq!(
5663 summary.copy_summary.directories_created, 1,
5664 "should create only root directory (not 'baz' with non-matching content)"
5665 );
5666 assert!(
5668 test_path.join("dst").join("foo").exists(),
5669 "foo should be linked"
5670 );
5671 assert!(
5673 !test_path.join("dst").join("baz").exists(),
5674 "baz directory should NOT be created (no matching content inside)"
5675 );
5676 Ok(())
5677 }
5678 #[tokio::test]
5681 #[traced_test]
5682 async fn test_dry_run_empty_dir_not_reported_as_created() -> Result<(), anyhow::Error> {
5683 let test_path = testutils::create_temp_dir().await?;
5684 let src_path = test_path.join("src");
5690 tokio::fs::create_dir(&src_path).await?;
5691 tokio::fs::write(src_path.join("foo"), "content").await?;
5692 tokio::fs::write(src_path.join("bar"), "content").await?;
5693 tokio::fs::create_dir(src_path.join("baz")).await?;
5694 let mut filter = FilterSettings::new();
5696 filter.add_include("foo").unwrap();
5697 let summary = link(
5698 &PROGRESS,
5699 &test_path,
5700 &src_path,
5701 &test_path.join("dst"),
5702 &None,
5703 &Settings {
5704 copy_settings: copy::Settings {
5705 reflink: Default::default(),
5706 local_copy_handoff: Default::default(),
5707 dereference: false,
5708 fail_early: false,
5709 overwrite: false,
5710 overwrite_compare: Default::default(),
5711 overwrite_filter: None,
5712 ignore_existing: false,
5713 chunk_size: 0,
5714 skip_specials: false,
5715 remote_copy_buffer_size: 0,
5716 filter: None,
5717 dry_run: None,
5718 delete: None,
5719 },
5720 update_compare: Default::default(),
5721 update_exclusive: false,
5722 filter: Some(filter),
5723 dry_run: Some(crate::config::DryRunMode::Explain),
5724 preserve: preserve::preserve_all(),
5725 },
5726 false,
5727 )
5728 .await?;
5729 assert_eq!(
5731 summary.hard_links_created, 1,
5732 "should report only 'foo' would be linked"
5733 );
5734 assert_eq!(
5735 summary.copy_summary.directories_created, 1,
5736 "should report only root directory would be created (not empty 'baz')"
5737 );
5738 assert!(
5740 !test_path.join("dst").exists(),
5741 "dst should not exist in dry-run"
5742 );
5743 Ok(())
5744 }
5745 #[tokio::test]
5748 #[traced_test]
5749 async fn test_existing_dir_not_removed_with_overwrite() -> Result<(), anyhow::Error> {
5750 let test_path = testutils::create_temp_dir().await?;
5751 let src_path = test_path.join("src");
5757 tokio::fs::create_dir(&src_path).await?;
5758 tokio::fs::write(src_path.join("foo"), "content").await?;
5759 tokio::fs::write(src_path.join("bar"), "content").await?;
5760 tokio::fs::create_dir(src_path.join("baz")).await?;
5761 let dst_path = test_path.join("dst");
5763 tokio::fs::create_dir(&dst_path).await?;
5764 tokio::fs::create_dir(dst_path.join("baz")).await?;
5765 tokio::fs::write(dst_path.join("baz").join("marker.txt"), "existing").await?;
5767 let mut filter = FilterSettings::new();
5769 filter.add_include("foo").unwrap();
5770 let summary = link(
5771 &PROGRESS,
5772 &test_path,
5773 &src_path,
5774 &dst_path,
5775 &None,
5776 &Settings {
5777 copy_settings: copy::Settings {
5778 reflink: Default::default(),
5779 local_copy_handoff: Default::default(),
5780 dereference: false,
5781 fail_early: false,
5782 overwrite: true, overwrite_compare: Default::default(),
5784 overwrite_filter: None,
5785 ignore_existing: false,
5786 chunk_size: 0,
5787 skip_specials: false,
5788 remote_copy_buffer_size: 0,
5789 filter: None,
5790 dry_run: None,
5791 delete: None,
5792 },
5793 update_compare: Default::default(),
5794 update_exclusive: false,
5795 filter: Some(filter),
5796 dry_run: None,
5797 preserve: preserve::preserve_all(),
5798 },
5799 false,
5800 )
5801 .await?;
5802 assert_eq!(summary.hard_links_created, 1, "should link only 'foo' file");
5804 assert_eq!(
5806 summary.copy_summary.directories_unchanged, 2,
5807 "root dst and baz directories should be unchanged"
5808 );
5809 assert_eq!(
5810 summary.copy_summary.directories_created, 0,
5811 "should not create any directories"
5812 );
5813 assert!(dst_path.join("foo").exists(), "foo should be linked");
5815 assert!(!dst_path.join("bar").exists(), "bar should not be linked");
5817 assert!(
5819 dst_path.join("baz").exists(),
5820 "existing baz directory should still exist"
5821 );
5822 assert!(
5823 dst_path.join("baz").join("marker.txt").exists(),
5824 "existing content in baz should still exist"
5825 );
5826 Ok(())
5827 }
5828
5829 async fn delegated_empty_directory_case(
5830 dry_run: bool,
5831 directly_included: bool,
5832 ) -> anyhow::Result<()> {
5833 for relative in ["docs", "a/docs"] {
5834 let test_path = testutils::create_temp_dir().await?;
5835 let src = test_path.join("src");
5836 let update = test_path.join("update");
5837 let dst = test_path.join("dst");
5838 tokio::fs::create_dir_all(src.join("a")).await?;
5839 tokio::fs::create_dir_all(update.join(relative)).await?;
5840 tokio::fs::write(update.join(relative).join("readme.md"), "FILTERED").await?;
5841 let mut filter = FilterSettings::new();
5842 filter.add_include("*.rs")?;
5843 if directly_included {
5844 filter.add_include(&format!("/{relative}"))?;
5845 }
5846 let mut settings = common_settings(false, false);
5847 settings.filter = Some(filter.clone());
5848 settings.copy_settings.filter = Some(filter);
5849 settings.dry_run = dry_run.then_some(crate::config::DryRunMode::Brief);
5850 settings.copy_settings.dry_run = settings.dry_run;
5851 let summary = link(
5852 &PROGRESS,
5853 &test_path,
5854 &src,
5855 &dst,
5856 &Some(update.clone()),
5857 &settings,
5858 false,
5859 )
5860 .await?;
5861 let expected_dirs = if directly_included {
5862 1 + std::path::Path::new(relative).components().count()
5863 } else {
5864 1
5865 };
5866 assert_eq!(summary.copy_summary.directories_created, expected_dirs);
5867 assert_eq!(summary.copy_summary.files_copied, 0);
5868 assert_eq!(summary.copy_summary.files_skipped, 1);
5869 assert_eq!(summary.hard_links_created, 0);
5870 assert_eq!(dst.exists(), !dry_run, "the true root must be retained");
5871 assert_eq!(dst.join(relative).exists(), !dry_run && directly_included);
5872 assert!(!dst.join(relative).join("readme.md").exists());
5873 if !directly_included {
5874 assert!(
5875 !dst.join("a").exists(),
5876 "empty ancestors must also be removed"
5877 );
5878 }
5879 let copy_dst = test_path.join("copy-root");
5881 let summary = copy::copy(
5882 &PROGRESS,
5883 &update.join(relative),
5884 ©_dst,
5885 &settings.copy_settings,
5886 &settings.preserve,
5887 false,
5888 )
5889 .await?;
5890 assert_eq!(summary.directories_created, 1);
5891 assert_eq!(copy_dst.exists(), !dry_run);
5892 }
5893 Ok(())
5894 }
5895
5896 #[tokio::test]
5897 async fn delegated_traversal_only_directories_are_removed() -> anyhow::Result<()> {
5898 delegated_empty_directory_case(false, false).await
5899 }
5900
5901 #[tokio::test]
5902 async fn delegated_traversal_only_directories_are_not_counted_in_dry_run()
5903 -> anyhow::Result<()> {
5904 delegated_empty_directory_case(true, false).await
5905 }
5906
5907 #[tokio::test]
5908 async fn delegated_directly_included_empty_directories_are_kept() -> anyhow::Result<()> {
5909 delegated_empty_directory_case(false, true).await?;
5910 delegated_empty_directory_case(true, true).await
5911 }
5912
5913 #[tokio::test]
5914 async fn delegated_reused_traversal_only_directory_is_kept() -> anyhow::Result<()> {
5915 let test_path = testutils::create_temp_dir().await?;
5916 let src = test_path.join("src");
5917 let update = test_path.join("update");
5918 let dst = test_path.join("dst");
5919 tokio::fs::create_dir(&src).await?;
5920 tokio::fs::create_dir_all(update.join("docs")).await?;
5921 tokio::fs::create_dir_all(dst.join("docs")).await?;
5922 tokio::fs::write(update.join("docs/readme.md"), "FILTERED").await?;
5923 tokio::fs::write(dst.join("docs/sentinel"), "KEEP").await?;
5924 let mut filter = FilterSettings::new();
5925 filter.add_include("*.rs")?;
5926 let mut settings = common_settings(false, true);
5927 settings.copy_settings.filter = Some(filter.clone());
5928 settings.filter = Some(filter);
5929 let summary = link(
5930 &PROGRESS,
5931 &test_path,
5932 &src,
5933 &dst,
5934 &Some(update),
5935 &settings,
5936 false,
5937 )
5938 .await?;
5939 assert_eq!(summary.copy_summary.directories_created, 0);
5940 assert_eq!(summary.copy_summary.directories_unchanged, 2);
5941 assert_eq!(tokio::fs::read(dst.join("docs/sentinel")).await?, b"KEEP");
5942 assert!(!dst.join("docs/readme.md").exists());
5943 Ok(())
5944 }
5945
5946 #[tokio::test]
5947 async fn delegated_empty_directory_cleanup_preserves_child_errors() -> anyhow::Result<()> {
5948 for dry_run in [false, true] {
5949 let test_path = testutils::create_temp_dir().await?;
5950 let src = test_path.join("src");
5951 let update = test_path.join("update");
5952 let dst = test_path.join("dst");
5953 tokio::fs::create_dir(&src).await?;
5954 tokio::fs::create_dir_all(update.join("docs")).await?;
5955 let _socket = std::os::unix::net::UnixListener::bind(update.join("docs/bad.rs"))?;
5956 let mut filter = FilterSettings::new();
5957 filter.add_include("*.rs")?;
5958 let mut settings = common_settings(false, false);
5959 settings.copy_settings.filter = Some(filter.clone());
5960 settings.filter = Some(filter);
5961 settings.dry_run = dry_run.then_some(crate::config::DryRunMode::Brief);
5962 settings.copy_settings.dry_run = settings.dry_run;
5963 let error = link(
5964 &PROGRESS,
5965 &test_path,
5966 &src,
5967 &dst,
5968 &Some(update),
5969 &settings,
5970 false,
5971 )
5972 .await
5973 .expect_err("empty-directory cleanup must preserve a failed child");
5974 assert!(format!("{:#}", error.source).contains("unsupported src file type"));
5975 assert_eq!(error.summary.copy_summary.directories_created, 1);
5976 assert_eq!(error.summary.copy_summary.files_copied, 0);
5977 assert!(!dst.join("docs").exists());
5978 assert_eq!(dst.exists(), !dry_run);
5979 }
5980 Ok(())
5981 }
5982
5983 #[tokio::test]
5989 #[traced_test]
5990 async fn update_only_excluded_entry_not_copied_without_delete() -> Result<(), anyhow::Error>
5991 {
5992 let test_path = testutils::create_temp_dir().await?;
5993 let src = test_path.join("src");
5997 let update = test_path.join("update");
5998 let dst = test_path.join("dst");
5999 tokio::fs::create_dir(&src).await?;
6000 tokio::fs::create_dir(&update).await?;
6001 tokio::fs::write(src.join("keep.txt"), "keep").await?;
6002 tokio::fs::write(update.join("keep.txt"), "keep").await?;
6003 tokio::fs::write(update.join("extra.txt"), "EXCLUDED").await?;
6004 tokio::fs::write(update.join("wanted.txt"), "wanted").await?;
6005
6006 let mut filter = FilterSettings::new();
6007 filter.add_exclude("extra.txt").unwrap();
6008 let mut settings = common_settings(false, false);
6009 settings.filter = Some(filter);
6010 assert!(settings.copy_settings.delete.is_none());
6012
6013 let summary = link(
6014 &PROGRESS,
6015 &test_path,
6016 &src,
6017 &dst,
6018 &Some(update.clone()),
6019 &settings,
6020 false,
6021 )
6022 .await?;
6023
6024 assert!(
6025 !dst.join("extra.txt").exists(),
6026 "update-only entry matching --exclude must NOT be copied when --delete is off"
6027 );
6028 assert!(
6029 dst.join("wanted.txt").exists(),
6030 "non-excluded update-only entry should be copied"
6031 );
6032 assert!(dst.join("keep.txt").exists(), "shared entry should exist");
6033 assert_eq!(
6034 summary.copy_summary.files_skipped, 1,
6035 "the excluded update-only file should be counted skipped"
6036 );
6037 Ok(())
6038 }
6039
6040 fn are_hardlinked(a: &std::path::Path, b: &std::path::Path) -> bool {
6042 use std::os::unix::fs::MetadataExt;
6043 match (std::fs::symlink_metadata(a), std::fs::symlink_metadata(b)) {
6044 (Ok(ma), Ok(mb)) => ma.ino() == mb.ino() && ma.dev() == mb.dev(),
6045 _ => false,
6046 }
6047 }
6048
6049 #[tokio::test]
6062 #[traced_test]
6063 async fn type_mismatch_excluded_update_dir_not_copied_src_file_kept()
6064 -> Result<(), anyhow::Error> {
6065 let test_path = testutils::create_temp_dir().await?;
6066 let src = test_path.join("src");
6067 let update = test_path.join("update");
6068 let dst = test_path.join("dst");
6069 tokio::fs::create_dir(&src).await?;
6070 tokio::fs::create_dir(&update).await?;
6071 tokio::fs::write(src.join("cache"), "SRC-FILE").await?;
6073 tokio::fs::create_dir(update.join("cache")).await?;
6074 tokio::fs::write(update.join("cache").join("inner.dat"), "EXCLUDED").await?;
6075 tokio::fs::write(src.join("keep.txt"), "keep").await?;
6077 tokio::fs::write(update.join("keep.txt"), "keep").await?;
6078 let keep_mtime = filetime::FileTime::from_unix_time(1_700_000_000, 0);
6084 filetime::set_file_mtime(src.join("keep.txt"), keep_mtime)?;
6085 filetime::set_file_mtime(update.join("keep.txt"), keep_mtime)?;
6086
6087 let mut filter = FilterSettings::new();
6088 filter.add_exclude("cache/").unwrap(); let mut settings = common_settings(false, false);
6090 settings.filter = Some(filter);
6091 assert!(settings.copy_settings.delete.is_none());
6092
6093 let summary = link(
6094 &PROGRESS,
6095 &test_path,
6096 &src,
6097 &dst,
6098 &Some(update.clone()),
6099 &settings,
6100 false,
6101 )
6102 .await?;
6103
6104 assert!(
6106 !dst.join("cache").join("inner.dat").exists(),
6107 "excluded update directory `cache/` must not be copied"
6108 );
6109 assert!(
6110 !dst.join("cache").is_dir(),
6111 "dst/cache must not be the excluded update directory"
6112 );
6113 assert!(
6115 dst.join("cache").is_file(),
6116 "src `cache` file must be materialized when the update dir is excluded"
6117 );
6118 assert_eq!(
6119 tokio::fs::read_to_string(dst.join("cache")).await?,
6120 "SRC-FILE"
6121 );
6122 assert!(
6123 are_hardlinked(&src.join("cache"), &dst.join("cache")),
6124 "the src `cache` file must be hard-linked into the destination"
6125 );
6126 assert!(
6127 dst.join("keep.txt").exists(),
6128 "shared entry should still link"
6129 );
6130 assert_eq!(summary.hard_links_created, 2);
6134 assert_eq!(summary.copy_summary.files_copied, 0);
6135 assert_eq!(
6136 summary.copy_summary.directories_created, 1,
6137 "only the dst root is created; the excluded `cache/` dir must not be"
6138 );
6139 Ok(())
6140 }
6141
6142 #[tokio::test]
6152 #[traced_test]
6153 async fn reverse_type_mismatch_excluded_update_file_not_copied_src_dir_kept()
6154 -> Result<(), anyhow::Error> {
6155 let test_path = testutils::create_temp_dir().await?;
6156 let src = test_path.join("src");
6157 let update = test_path.join("update");
6158 let dst = test_path.join("dst");
6159 tokio::fs::create_dir(&src).await?;
6160 tokio::fs::create_dir(&update).await?;
6161 tokio::fs::create_dir(src.join("data")).await?;
6163 tokio::fs::write(src.join("data").join("inner.txt"), "SRC-DIR-CONTENT").await?;
6164 tokio::fs::write(update.join("data"), "UPDATE-FILE-EXCLUDED").await?;
6165
6166 let mut filter = FilterSettings::new();
6170 filter.add_include("data/").unwrap();
6171 filter.add_include("data/**").unwrap();
6172 let mut settings = common_settings(false, false);
6173 settings.filter = Some(filter);
6174 assert!(settings.copy_settings.delete.is_none());
6175
6176 link(
6177 &PROGRESS,
6178 &test_path,
6179 &src,
6180 &dst,
6181 &Some(update.clone()),
6182 &settings,
6183 false,
6184 )
6185 .await?;
6186
6187 assert!(
6189 dst.join("data").is_dir(),
6190 "src `data` directory must be materialized when the update file is excluded"
6191 );
6192 assert!(
6193 dst.join("data").join("inner.txt").exists(),
6194 "src directory contents must be linked through"
6195 );
6196 assert!(
6197 are_hardlinked(
6198 &src.join("data").join("inner.txt"),
6199 &dst.join("data").join("inner.txt")
6200 ),
6201 "src directory's file must be hard-linked into the destination"
6202 );
6203 Ok(())
6204 }
6205
6206 #[tokio::test]
6212 #[traced_test]
6213 async fn type_mismatch_excluded_update_dir_update_exclusive_materializes_nothing()
6214 -> Result<(), anyhow::Error> {
6215 let test_path = testutils::create_temp_dir().await?;
6216 let src = test_path.join("src");
6217 let update = test_path.join("update");
6218 let dst = test_path.join("dst");
6219 tokio::fs::create_dir(&src).await?;
6220 tokio::fs::create_dir(&update).await?;
6221 tokio::fs::write(src.join("cache"), "SRC-FILE").await?;
6222 tokio::fs::create_dir(update.join("cache")).await?;
6223 tokio::fs::write(update.join("cache").join("inner.dat"), "EXCLUDED").await?;
6224 tokio::fs::write(update.join("wanted.txt"), "wanted").await?;
6226
6227 let mut filter = FilterSettings::new();
6228 filter.add_exclude("cache/").unwrap();
6229 let mut settings = common_settings(false, false);
6230 settings.update_exclusive = true;
6231 settings.filter = Some(filter);
6232
6233 link(
6234 &PROGRESS,
6235 &test_path,
6236 &src,
6237 &dst,
6238 &Some(update.clone()),
6239 &settings,
6240 false,
6241 )
6242 .await?;
6243
6244 assert!(
6245 !dst.join("cache").exists(),
6246 "under --update-exclusive an excluded-update type-mismatch must materialize nothing \
6247 (no excluded dir, no stale src file)"
6248 );
6249 assert!(
6250 dst.join("wanted.txt").exists(),
6251 "filter-passing update-only entries are still copied under --update-exclusive"
6252 );
6253 Ok(())
6254 }
6255
6256 #[tokio::test]
6263 #[traced_test]
6264 async fn type_mismatch_excluded_update_dir_delete_keeps_src_file()
6265 -> Result<(), anyhow::Error> {
6266 let test_path = testutils::create_temp_dir().await?;
6267 let src = test_path.join("src");
6268 let update = test_path.join("update");
6269 let dst = test_path.join("dst");
6270 tokio::fs::create_dir(&src).await?;
6271 tokio::fs::create_dir(&update).await?;
6272 tokio::fs::create_dir(&dst).await?;
6273 tokio::fs::write(src.join("cache"), "SRC-FILE").await?;
6274 tokio::fs::create_dir(update.join("cache")).await?;
6275 tokio::fs::write(update.join("cache").join("inner.dat"), "EXCLUDED").await?;
6276 tokio::fs::write(dst.join("stale.txt"), "stale").await?;
6278
6279 let mut filter = FilterSettings::new();
6280 filter.add_exclude("cache/").unwrap();
6281 let mut settings = common_settings(false, true); settings.filter = Some(filter);
6283 settings.copy_settings.delete = Some(copy::DeleteSettings {
6284 delete_excluded: false,
6285 });
6286
6287 link(
6288 &PROGRESS,
6289 &test_path,
6290 &src,
6291 &dst,
6292 &Some(update.clone()),
6293 &settings,
6294 false,
6295 )
6296 .await?;
6297
6298 assert!(
6299 dst.join("cache").is_file(),
6300 "src `cache` file must survive --delete (kept in the keep-set, not pruned)"
6301 );
6302 assert_eq!(
6303 tokio::fs::read_to_string(dst.join("cache")).await?,
6304 "SRC-FILE"
6305 );
6306 assert!(
6307 !dst.join("cache").is_dir(),
6308 "the excluded update directory must leave no leftover"
6309 );
6310 assert!(
6311 !dst.join("stale.txt").exists(),
6312 "extraneous dst entry must be pruned by --delete"
6313 );
6314 Ok(())
6315 }
6316 }
6317 mod dry_run_tests {
6318 use super::*;
6319
6320 #[tokio::test]
6321 async fn update_delete_preview_keeps_direct_and_delegated_pruning_beneath_outer_dst()
6322 -> Result<(), anyhow::Error> {
6323 let root = testutils::create_temp_dir().await?;
6324 let src = root.join("src");
6325 let update = root.join("update");
6326 let outside = root.join("outside");
6327 let dst = root.join("dst");
6328 tokio::fs::create_dir_all(src.join("direct")).await?;
6329 tokio::fs::create_dir_all(update.join("delegated")).await?;
6330 tokio::fs::create_dir_all(outside.join("direct")).await?;
6331 tokio::fs::create_dir_all(outside.join("delegated")).await?;
6332 tokio::fs::write(outside.join("direct/stale"), "DIRECT-OUTSIDE").await?;
6333 tokio::fs::write(outside.join("delegated/stale"), "DELEGATED-OUTSIDE").await?;
6334 tokio::fs::symlink(&outside, &dst).await?;
6335 let mut settings = common_settings(false, true);
6336 settings.dry_run = Some(crate::config::DryRunMode::Brief);
6337 settings.copy_settings.dry_run = settings.dry_run;
6338 settings.copy_settings.delete = Some(copy::DeleteSettings {
6339 delete_excluded: false,
6340 });
6341 let summary = link(
6342 &PROGRESS,
6343 &root,
6344 &src,
6345 &dst,
6346 &Some(update.clone()),
6347 &settings,
6348 false,
6349 )
6350 .await?;
6351 assert_eq!(summary.copy_summary.rm_summary.files_removed, 0);
6352 assert_eq!(
6353 tokio::fs::read_to_string(outside.join("direct/stale")).await?,
6354 "DIRECT-OUTSIDE"
6355 );
6356 assert_eq!(
6357 tokio::fs::read_to_string(outside.join("delegated/stale")).await?,
6358 "DELEGATED-OUTSIDE"
6359 );
6360
6361 let real_dst = root.join("real-dst");
6362 tokio::fs::create_dir_all(real_dst.join("direct")).await?;
6363 tokio::fs::create_dir_all(real_dst.join("delegated")).await?;
6364 tokio::fs::write(real_dst.join("delegated/stale"), "INSIDE-STALE").await?;
6365 let real_summary = link(
6366 &PROGRESS,
6367 &root,
6368 &src,
6369 &real_dst,
6370 &Some(update),
6371 &settings,
6372 false,
6373 )
6374 .await?;
6375 assert_eq!(real_summary.copy_summary.rm_summary.files_removed, 1);
6376 assert_eq!(
6377 tokio::fs::read_to_string(real_dst.join("delegated/stale")).await?,
6378 "INSIDE-STALE"
6379 );
6380 Ok(())
6381 }
6382
6383 #[tokio::test]
6384 async fn update_exclusive_delete_preview_keeps_selected_shared_file()
6385 -> Result<(), anyhow::Error> {
6386 let root = testutils::create_temp_dir().await?;
6387 let src = root.join("src");
6388 let update = root.join("update");
6389 let dst = root.join("dst");
6390 tokio::fs::create_dir(&src).await?;
6391 tokio::fs::create_dir(&update).await?;
6392 tokio::fs::create_dir(&dst).await?;
6393 tokio::fs::write(src.join("shared"), b"old").await?;
6394 tokio::fs::write(update.join("shared"), b"replacement").await?;
6395 tokio::fs::write(dst.join("shared"), b"destination").await?;
6396 tokio::fs::write(dst.join("stale"), b"stale").await?;
6397
6398 let mut settings = common_settings(false, false);
6399 settings.update_exclusive = true;
6400 settings.dry_run = Some(crate::config::DryRunMode::Brief);
6401 settings.copy_settings.dry_run = settings.dry_run;
6402 settings.copy_settings.delete = Some(copy::DeleteSettings {
6403 delete_excluded: false,
6404 });
6405
6406 let summary = link(
6407 &PROGRESS,
6408 &root,
6409 &src,
6410 &dst,
6411 &Some(update),
6412 &settings,
6413 false,
6414 )
6415 .await?;
6416
6417 assert_eq!(summary.hard_links_created, 0);
6418 assert_eq!(summary.copy_summary.files_copied, 1);
6419 assert_eq!(summary.copy_summary.rm_summary.files_removed, 1);
6420 assert!(dst.join("shared").exists());
6421 assert!(dst.join("stale").exists());
6422 Ok(())
6423 }
6424
6425 #[tokio::test]
6426 async fn update_exclusive_delete_preview_omits_source_only_file()
6427 -> Result<(), anyhow::Error> {
6428 let root = testutils::create_temp_dir().await?;
6429 let src = root.join("src");
6430 let update = root.join("update");
6431 let dst = root.join("dst");
6432 tokio::fs::create_dir(&src).await?;
6433 tokio::fs::create_dir(&update).await?;
6434 tokio::fs::create_dir(&dst).await?;
6435 tokio::fs::write(src.join("source-only"), b"source").await?;
6436 tokio::fs::write(dst.join("source-only"), b"destination").await?;
6437
6438 let mut settings = common_settings(false, false);
6439 settings.update_exclusive = true;
6440 settings.dry_run = Some(crate::config::DryRunMode::Brief);
6441 settings.copy_settings.dry_run = settings.dry_run;
6442 settings.copy_settings.delete = Some(copy::DeleteSettings {
6443 delete_excluded: false,
6444 });
6445
6446 let summary = link(
6447 &PROGRESS,
6448 &root,
6449 &src,
6450 &dst,
6451 &Some(update),
6452 &settings,
6453 false,
6454 )
6455 .await?;
6456
6457 assert_eq!(summary.hard_links_created, 0);
6458 assert_eq!(summary.copy_summary.files_copied, 0);
6459 assert_eq!(summary.copy_summary.rm_summary.files_removed, 1);
6460 assert!(dst.join("source-only").exists());
6461 Ok(())
6462 }
6463
6464 #[tokio::test]
6466 #[traced_test]
6467 async fn test_dry_run_file_does_not_create_link() -> Result<(), anyhow::Error> {
6468 let tmp_dir = testutils::setup_test_dir().await?;
6469 let test_path = tmp_dir.as_path();
6470 let src_file = test_path.join("foo/0.txt");
6471 let dst_file = test_path.join("dst_link.txt");
6472 assert!(
6474 !dst_file.exists(),
6475 "destination should not exist before dry-run"
6476 );
6477 let summary = link(
6478 &PROGRESS,
6479 test_path,
6480 &src_file,
6481 &dst_file,
6482 &None,
6483 &Settings {
6484 copy_settings: CopySettings {
6485 reflink: Default::default(),
6486 local_copy_handoff: Default::default(),
6487 dereference: false,
6488 fail_early: false,
6489 overwrite: false,
6490 overwrite_compare: Default::default(),
6491 overwrite_filter: None,
6492 ignore_existing: false,
6493 chunk_size: 0,
6494 skip_specials: false,
6495 remote_copy_buffer_size: 0,
6496 filter: None,
6497 dry_run: None,
6498 delete: None,
6499 },
6500 update_compare: Default::default(),
6501 update_exclusive: false,
6502 filter: None,
6503 dry_run: Some(crate::config::DryRunMode::Brief),
6504 preserve: preserve::preserve_all(),
6505 },
6506 false,
6507 )
6508 .await?;
6509 assert!(!dst_file.exists(), "dry-run should not create hard link");
6511 assert_eq!(
6513 summary.hard_links_created, 1,
6514 "dry-run should report 1 hard link that would be created"
6515 );
6516 Ok(())
6517 }
6518 #[tokio::test]
6520 #[traced_test]
6521 async fn test_dry_run_directory_does_not_create_destination() -> Result<(), anyhow::Error> {
6522 let tmp_dir = testutils::setup_test_dir().await?;
6523 let test_path = tmp_dir.as_path();
6524 let dst_path = test_path.join("nonexistent_dst");
6525 assert!(
6527 !dst_path.exists(),
6528 "destination should not exist before dry-run"
6529 );
6530 let summary = link(
6531 &PROGRESS,
6532 test_path,
6533 &test_path.join("foo"),
6534 &dst_path,
6535 &None,
6536 &Settings {
6537 copy_settings: CopySettings {
6538 reflink: Default::default(),
6539 local_copy_handoff: Default::default(),
6540 dereference: false,
6541 fail_early: false,
6542 overwrite: false,
6543 overwrite_compare: Default::default(),
6544 overwrite_filter: None,
6545 ignore_existing: false,
6546 chunk_size: 0,
6547 skip_specials: false,
6548 remote_copy_buffer_size: 0,
6549 filter: None,
6550 dry_run: None,
6551 delete: None,
6552 },
6553 update_compare: Default::default(),
6554 update_exclusive: false,
6555 filter: None,
6556 dry_run: Some(crate::config::DryRunMode::Brief),
6557 preserve: preserve::preserve_all(),
6558 },
6559 false,
6560 )
6561 .await?;
6562 assert!(
6564 !dst_path.exists(),
6565 "dry-run should not create destination directory"
6566 );
6567 assert!(
6569 summary.hard_links_created > 0,
6570 "dry-run should report hard links that would be created"
6571 );
6572 Ok(())
6573 }
6574 #[tokio::test]
6576 #[traced_test]
6577 async fn test_dry_run_symlinks_counted_correctly() -> Result<(), anyhow::Error> {
6578 let tmp_dir = testutils::setup_test_dir().await?;
6579 let test_path = tmp_dir.as_path();
6580 let src_path = test_path.join("foo/baz");
6582 let dst_path = test_path.join("dst_baz");
6583 assert!(
6585 !dst_path.exists(),
6586 "destination should not exist before dry-run"
6587 );
6588 let summary = link(
6589 &PROGRESS,
6590 test_path,
6591 &src_path,
6592 &dst_path,
6593 &None,
6594 &Settings {
6595 copy_settings: CopySettings {
6596 reflink: Default::default(),
6597 local_copy_handoff: Default::default(),
6598 dereference: false,
6599 fail_early: false,
6600 overwrite: false,
6601 overwrite_compare: Default::default(),
6602 overwrite_filter: None,
6603 ignore_existing: false,
6604 chunk_size: 0,
6605 skip_specials: false,
6606 remote_copy_buffer_size: 0,
6607 filter: None,
6608 dry_run: None,
6609 delete: None,
6610 },
6611 update_compare: Default::default(),
6612 update_exclusive: false,
6613 filter: None,
6614 dry_run: Some(crate::config::DryRunMode::Brief),
6615 preserve: preserve::preserve_all(),
6616 },
6617 false,
6618 )
6619 .await?;
6620 assert!(!dst_path.exists(), "dry-run should not create destination");
6622 assert_eq!(
6624 summary.hard_links_created, 1,
6625 "dry-run should report 1 hard link (for 4.txt)"
6626 );
6627 assert_eq!(
6628 summary.copy_summary.symlinks_created, 2,
6629 "dry-run should report 2 symlinks (5.txt and 6.txt)"
6630 );
6631 Ok(())
6632 }
6633 }
6634
6635 #[tokio::test]
6642 #[traced_test]
6643 async fn test_fail_early_preserves_summary_from_failing_subtree() -> Result<(), anyhow::Error> {
6644 let tmp_dir = testutils::create_temp_dir().await?;
6645 let test_path = tmp_dir.as_path();
6646 let src_dir = test_path.join("src");
6651 let sub_dir = src_dir.join("sub");
6652 let bad_dir = sub_dir.join("unreadable_dir");
6653 tokio::fs::create_dir_all(&bad_dir).await?;
6654 tokio::fs::write(sub_dir.join("good.txt"), "content").await?;
6655 tokio::fs::write(bad_dir.join("f.txt"), "data").await?;
6656 tokio::fs::set_permissions(&bad_dir, std::fs::Permissions::from_mode(0o000)).await?;
6657 let dst_dir = test_path.join("dst");
6658 let result = link(
6659 &PROGRESS,
6660 test_path,
6661 &src_dir,
6662 &dst_dir,
6663 &None,
6664 &Settings {
6665 copy_settings: CopySettings {
6666 fail_early: true,
6667 ..common_settings(false, false).copy_settings
6668 },
6669 ..common_settings(false, false)
6670 },
6671 false,
6672 )
6673 .await;
6674 tokio::fs::set_permissions(&bad_dir, std::fs::Permissions::from_mode(0o755)).await?;
6676 let error = result.expect_err("link should fail due to unreadable directory");
6677 assert!(
6682 error.summary.copy_summary.directories_created >= 2,
6683 "fail-early summary should include directories from the failing subtree, \
6684 got directories_created={} (expected >= 2: dst/ and dst/sub/)",
6685 error.summary.copy_summary.directories_created
6686 );
6687 Ok(())
6688 }
6689
6690 #[tokio::test]
6691 #[traced_test]
6692 async fn skip_specials_skips_socket_in_link() -> Result<(), anyhow::Error> {
6693 let tmp_dir = testutils::setup_test_dir().await?;
6694 let test_path = tmp_dir.as_path();
6695 let src = test_path.join("src_dir");
6696 let dst = test_path.join("dst_dir");
6697 tokio::fs::create_dir(&src).await?;
6698 tokio::fs::write(src.join("file.txt"), "hello").await?;
6699 let _listener = std::os::unix::net::UnixListener::bind(src.join("test.sock"))?;
6700 let mut settings = common_settings(false, false);
6701 settings.copy_settings.skip_specials = true;
6702 let summary = link(&PROGRESS, test_path, &src, &dst, &None, &settings, false).await?;
6703 assert_eq!(summary.hard_links_created, 1);
6704 assert_eq!(summary.copy_summary.specials_skipped, 1);
6705 assert!(dst.join("file.txt").exists());
6706 assert!(!dst.join("test.sock").exists());
6707 Ok(())
6708 }
6709
6710 #[tokio::test]
6711 #[traced_test]
6712 async fn delete_skips_pruning_when_link_has_errors() -> Result<(), anyhow::Error> {
6713 let tmp_dir = testutils::setup_test_dir().await?;
6714 let test_path = tmp_dir.as_path();
6715 let src = test_path.join("foo");
6716 let dst = test_path.join("bar");
6717 link(
6719 &PROGRESS,
6720 test_path,
6721 &src,
6722 &dst,
6723 &None,
6724 &common_settings(false, false),
6725 false,
6726 )
6727 .await?;
6728 tokio::fs::write(dst.join("extraneous.txt"), b"junk").await?;
6730 let unreadable = src.join("baz");
6734 let original = tokio::fs::metadata(&unreadable).await?.permissions();
6735 tokio::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).await?;
6736
6737 let delete_settings = Settings {
6738 copy_settings: CopySettings {
6739 overwrite: true,
6740 fail_early: false,
6741 delete: Some(copy::DeleteSettings {
6742 delete_excluded: false,
6743 }),
6744 ..common_settings(false, true).copy_settings
6745 },
6746 ..common_settings(false, true)
6747 };
6748 let result = link(
6749 &PROGRESS,
6750 test_path,
6751 &src,
6752 &dst,
6753 &None,
6754 &delete_settings,
6755 false,
6756 )
6757 .await;
6758
6759 tokio::fs::set_permissions(&unreadable, original).await?;
6760
6761 assert!(
6762 result.is_err(),
6763 "link of the unreadable directory should fail"
6764 );
6765 assert!(
6766 dst.join("extraneous.txt").exists(),
6767 "pruning must be skipped when the link/update pass reported errors"
6768 );
6769 assert!(logs_contain(
6770 "because entry processing failed or did not provide complete exact names"
6771 ));
6772 Ok(())
6773 }
6774
6775 #[tokio::test]
6776 #[traced_test]
6777 async fn skip_specials_top_level_socket_in_link() -> Result<(), anyhow::Error> {
6778 let tmp_dir = testutils::setup_test_dir().await?;
6779 let test_path = tmp_dir.as_path();
6780 let src_socket = test_path.join("test.sock");
6781 let dst = test_path.join("dst.sock");
6782 let _listener = std::os::unix::net::UnixListener::bind(&src_socket)?;
6783 let mut settings = common_settings(false, false);
6784 settings.copy_settings.skip_specials = true;
6785 let summary = link(
6786 &PROGRESS,
6787 test_path,
6788 &src_socket,
6789 &dst,
6790 &None,
6791 &settings,
6792 false,
6793 )
6794 .await?;
6795 assert_eq!(summary.copy_summary.specials_skipped, 1);
6796 assert_eq!(summary.hard_links_created, 0);
6797 assert!(!dst.exists());
6798 Ok(())
6799 }
6800
6801 mod max_files_in_flight_tests {
6803 use super::*;
6804
6805 fn available_open_file_capacity(capacity: usize) -> usize {
6806 let waker = futures::task::noop_waker();
6807 let mut context = std::task::Context::from_waker(&waker);
6808 let mut permits = Vec::new();
6809 for _ in 0..capacity {
6810 let mut permit = Box::pin(throttle::open_file_permit());
6811 match std::future::Future::poll(permit.as_mut(), &mut context) {
6812 std::task::Poll::Ready(permit) => permits.push(permit),
6813 std::task::Poll::Pending => break,
6814 }
6815 }
6816 permits.len()
6817 }
6818
6819 async fn reacquire_all_open_file_capacity(
6820 admission: &testutils::AdmissionLimit,
6821 capacity: usize,
6822 ) -> Result<(), anyhow::Error> {
6823 let permits = admission
6824 .run_with_timeout(std::time::Duration::from_secs(20), async {
6825 let mut permits = Vec::new();
6826 for _ in 0..capacity {
6827 permits.push(throttle::open_file_permit().await);
6828 }
6829 permits
6830 })
6831 .await
6832 .context("link operation did not return all open-file capacity")?;
6833 drop(permits);
6834 Ok(())
6835 }
6836
6837 #[tokio::test]
6838 async fn update_directory_transition_retains_exact_handle_and_held_admission()
6839 -> anyhow::Result<()> {
6840 use std::os::fd::AsRawFd as _;
6841
6842 let root = testutils::create_temp_dir().await?;
6843 tokio::fs::write(root.join("source"), b"source").await?;
6844 tokio::fs::create_dir(root.join("update")).await?;
6845 let admission = testutils::AdmissionLimit::new().await;
6846 admission.set_files_in_flight(1);
6847 let parent = Dir::open_root_dir(&root, false, congestion::Side::Source).await?;
6848 let src_handle = parent.child(std::ffi::OsStr::new("source")).await?;
6849 let update_handle = parent.child(std::ffi::OsStr::new("update")).await?;
6850 let src_fd = src_handle.as_fd().as_raw_fd();
6851 let update_fd = update_handle.as_fd().as_raw_fd();
6852 let src_probe = testutils::FdIdentityProbe::capture(src_fd);
6853 let update_probe = testutils::FdIdentityProbe::capture(update_fd);
6854 let (src_probe, update_probe) = match (src_probe, update_probe) {
6855 (Ok(src_probe), Ok(update_probe)) => (src_probe, update_probe),
6856 (src_probe, update_probe) => {
6857 let probe_error = match src_probe {
6858 Err(error) => error,
6859 Ok(_) => match update_probe {
6860 Err(error) => error,
6861 Ok(_) => {
6862 unreachable!("at least one fd identity probe must have failed")
6863 }
6864 },
6865 };
6866 drop(src_handle);
6867 drop(update_handle);
6868 drop(parent);
6869 drop(admission);
6870 let cleanup_result = tokio::fs::remove_dir_all(root).await;
6871 return match cleanup_result {
6872 Ok(()) => Err(probe_error.into()),
6873 Err(cleanup_error) => Err(anyhow::Error::new(probe_error).context(
6874 format!("link fd-lifetime fixture did not clean up: {cleanup_error:#}"),
6875 )),
6876 };
6877 }
6878 };
6879 let mut entry = AdmittedLinkEntry::new(
6880 src_handle,
6881 Some(LeafPermit::OpenFile(throttle::open_file_permit().await)),
6882 );
6883 entry.update_handle = Some(update_handle);
6884
6885 let update_entry = entry.into_update_entry();
6886 let retained_directory = update_entry.kind() == EntryKind::Dir;
6887 let transferred_held_admission = update_entry.admission().is_some();
6888 let source_closed = src_probe.original_is_closed();
6890 let update_stayed_open = update_probe.original_is_closed().map(|closed| !closed);
6891 let mut next_permit = Box::pin(throttle::open_file_permit());
6892 let (capacity_stayed_held, early_permit) = match futures::poll!(next_permit.as_mut()) {
6893 std::task::Poll::Pending => (true, None),
6894 std::task::Poll::Ready(permit) => (false, Some(permit)),
6895 };
6896 drop(update_entry);
6897 let update_closed = update_probe.original_is_closed();
6898 let reacquire_result = match early_permit {
6899 Some(permit) => Ok(permit),
6900 None => {
6901 tokio::time::timeout(std::time::Duration::from_secs(1), next_permit.as_mut())
6902 .await
6903 .context("the delegated directory did not return open-file capacity")
6904 }
6905 };
6906 let reacquire_result = reacquire_result.map(drop);
6907 drop(parent);
6908 drop(admission);
6909 let cleanup_result = tokio::fs::remove_dir_all(root).await;
6910 let source_closed = source_closed?;
6911 let update_stayed_open = update_stayed_open?;
6912 let update_closed = update_closed?;
6913 reacquire_result?;
6914 cleanup_result?;
6915 assert!(
6916 retained_directory,
6917 "the admitted update owner lost its authoritative directory type"
6918 );
6919 assert!(transferred_held_admission);
6920 assert!(source_closed);
6921 assert!(update_stayed_open);
6922 assert!(update_closed);
6923 assert!(
6924 capacity_stayed_held,
6925 "the admitted update owner released capacity before copy dispatch"
6926 );
6927 Ok(())
6928 }
6929
6930 #[tokio::test]
6932 async fn filtered_hinted_file_does_not_wait_for_admission() -> Result<(), anyhow::Error> {
6933 let root = testutils::create_temp_dir().await?;
6934 let src = root.join("src");
6935 tokio::fs::create_dir(&src).await?;
6936 tokio::fs::write(src.join("leaf"), b"x").await?;
6937 let admission = testutils::AdmissionLimit::new().await;
6938 admission.set_files_in_flight(1);
6939 let held = throttle::open_file_permit().await;
6940 let src_dir =
6941 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
6942 let hints = src_dir.read_entries().await?;
6943 assert_eq!(
6944 hints,
6945 vec![(std::ffi::OsString::from("leaf"), Some(EntryKind::File))],
6946 "the fixture filesystem must provide the reliable hint this test exercises"
6947 );
6948 let mut filter = crate::filter::FilterSettings::new();
6949 filter.add_exclude("leaf")?;
6950 let mut settings = common_settings(false, false);
6951 settings.filter = Some(filter.clone());
6952 settings.copy_settings.filter = Some(filter);
6953 let dst = root.join("dst");
6954 let operation = link_dir_contents(
6955 &PROGRESS,
6956 &src_dir,
6957 src_dir.meta().await?,
6958 None,
6959 None,
6960 None,
6961 std::ffi::OsStr::new("dst"),
6962 &src,
6963 &dst,
6964 None,
6965 std::path::Path::new(""),
6966 &src,
6967 &dst,
6968 false,
6969 false,
6970 None,
6971 &settings,
6972 Summary::default(),
6973 SourceEntries::Live,
6974 UpdateEntries::Live,
6975 None,
6976 copy::DestinationContext::new(&dst),
6977 );
6978 let result = admission
6979 .run_with_timeout(std::time::Duration::from_secs(1), operation)
6980 .await;
6981 drop(held);
6982 let summary = result.context("rlink filter skip waited for open-file admission")??;
6983 assert_eq!(summary.copy_summary.files_skipped, 1);
6984 assert_eq!(summary.hard_links_created, 0);
6985 Ok(())
6986 }
6987
6988 #[tokio::test]
6990 async fn filtered_hinted_update_file_does_not_wait_for_admission()
6991 -> Result<(), anyhow::Error> {
6992 let root = testutils::create_temp_dir().await?;
6993 let src = root.join("src");
6994 let update = root.join("update");
6995 tokio::fs::create_dir(&src).await?;
6996 tokio::fs::create_dir(&update).await?;
6997 tokio::fs::write(update.join("leaf"), b"x").await?;
6998 let admission = testutils::AdmissionLimit::new().await;
6999 admission.set_files_in_flight(1);
7000 let held = throttle::open_file_permit().await;
7001 let src_dir =
7002 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7003 let update_dir =
7004 Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
7005 let hints = update_dir.read_entries().await?;
7006 assert_eq!(
7007 hints,
7008 vec![(std::ffi::OsString::from("leaf"), Some(EntryKind::File))],
7009 "the fixture filesystem must provide the reliable hint this test exercises"
7010 );
7011 let mut filter = crate::filter::FilterSettings::new();
7012 filter.add_exclude("leaf")?;
7013 let mut settings = common_settings(false, false);
7014 settings.filter = Some(filter.clone());
7015 settings.copy_settings.filter = Some(filter);
7016 let dst = root.join("dst");
7017 let operation = crate::task_scope::scope_tasks(link_dir_contents(
7018 &PROGRESS,
7019 &src_dir,
7020 update_dir.meta().await?,
7021 Some(&update_dir),
7022 None,
7023 None,
7024 std::ffi::OsStr::new("dst"),
7025 &src,
7026 &dst,
7027 Some(&update),
7028 std::path::Path::new(""),
7029 &src,
7030 &dst,
7031 false,
7032 false,
7033 None,
7034 &settings,
7035 Summary::default(),
7036 SourceEntries::Live,
7037 UpdateEntries::Live,
7038 None,
7039 copy::DestinationContext::new(&dst),
7040 ));
7041 let result = admission
7042 .run_with_timeout(std::time::Duration::from_secs(1), operation)
7043 .await;
7044 drop(held);
7045 let summary =
7046 result.context("rlink update filter skip waited for open-file admission")??;
7047 assert_eq!(summary.copy_summary.files_skipped, 1);
7048 assert_eq!(summary.copy_summary.files_copied, 0);
7049 Ok(())
7050 }
7051
7052 #[test]
7053 fn source_directory_hint_requires_admission_only_for_a_dual_tree_decision() {
7054 assert!(matches!(
7055 source_entry_admission(Some(EntryKind::Dir), true),
7056 EntryAdmission::RootOrDelegated
7057 ));
7058 assert!(matches!(
7059 source_entry_admission(Some(EntryKind::Dir), false),
7060 EntryAdmission::HintedDirectory
7061 ));
7062 }
7063
7064 #[tokio::test]
7066 async fn hinted_directory_classifies_while_pool_is_saturated() -> Result<(), anyhow::Error>
7067 {
7068 let root = testutils::create_temp_dir().await?;
7069 let src_path = root.join("src");
7070 let dst_path = root.join("dst");
7071 tokio::fs::create_dir(&src_path).await?;
7072 let admission = testutils::AdmissionLimit::new().await;
7073 admission.set_files_in_flight(1);
7074 let held = throttle::open_file_permit().await;
7075 let src_parent = Arc::new(
7076 Dir::open_parent_dir(&root, congestion::Side::Source)
7077 .await?
7078 .into_tree(),
7079 );
7080 let mut settings = common_settings(false, false);
7081 settings.dry_run = Some(crate::config::DryRunMode::Brief);
7082 settings.copy_settings.dry_run = settings.dry_run;
7083 let result = admission
7084 .run_with_timeout(
7085 std::time::Duration::from_secs(1),
7086 link_internal(
7087 &PROGRESS,
7088 &src_parent,
7089 None,
7090 None,
7091 std::ffi::OsStr::new("src"),
7092 &src_path,
7093 &dst_path,
7094 None,
7095 std::path::Path::new(""),
7096 UpdateRootRequirement::Optional,
7097 &settings,
7098 false,
7099 walk::EntryAdmission::HintedDirectory.into(),
7100 copy::DestinationContext::new(&dst_path),
7101 ),
7102 )
7103 .await;
7104 drop(held);
7105 let summary = result.context("hinted rlink directory waited for admission")??;
7106 assert_eq!(summary.summary.copy_summary.directories_created, 1);
7107 Ok(())
7108 }
7109
7110 #[tokio::test(flavor = "current_thread")]
7113 async fn hinted_source_with_update_admits_before_source_classification()
7114 -> Result<(), anyhow::Error> {
7115 let root = testutils::create_temp_dir().await?;
7116 let src_root = root.join("src");
7117 let update_root = root.join("update");
7118 let dst_root = root.join("dst");
7119 tokio::fs::create_dir(&src_root).await?;
7120 tokio::fs::create_dir(&update_root).await?;
7121 tokio::fs::create_dir(src_root.join("entry")).await?;
7122 tokio::fs::write(update_root.join("entry"), b"x").await?;
7123
7124 let admission = testutils::AdmissionLimit::new().await;
7125 admission.set_files_in_flight(1);
7126 let stat_resource =
7127 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7128 admission.set_max_ops_in_flight(stat_resource, 1);
7129 let src_parent =
7130 Arc::new(Dir::open_root_dir(&src_root, false, congestion::Side::Source).await?);
7131 let update_parent =
7132 Arc::new(Dir::open_root_dir(&update_root, false, congestion::Side::Source).await?);
7133 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7134 let mut settings = common_settings(false, false);
7135 settings.dry_run = Some(crate::config::DryRunMode::Brief);
7136 settings.copy_settings.dry_run = settings.dry_run;
7137
7138 let operation = link_internal(
7139 &PROGRESS,
7140 &src_parent,
7141 Some((&update_parent, std::ffi::OsStr::new("entry"))),
7142 None,
7143 std::ffi::OsStr::new("entry"),
7144 &src_root,
7145 &dst_root,
7146 Some(&update_root),
7147 std::path::Path::new("entry"),
7148 UpdateRootRequirement::Optional,
7149 &settings,
7150 false,
7151 EntryAdmission::HintedDirectory.into(),
7152 copy::DestinationContext::parent(None),
7153 );
7154 tokio::pin!(operation);
7155 assert!(
7156 futures::poll!(operation.as_mut()).is_pending(),
7157 "source classification must stop at the saturated Stat gate"
7158 );
7159 let mut permit_probe = Box::pin(throttle::open_file_permit());
7160 let admitted_before_source = futures::poll!(permit_probe.as_mut()).is_pending();
7161 drop(permit_probe);
7162
7163 drop(held_stat);
7164 let summary = admission
7165 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7166 .await
7167 .context("rlink did not resume after source classification was released")??;
7168 assert!(
7169 admitted_before_source,
7170 "the hinted source opened before admission for its separate update decision"
7171 );
7172 assert_eq!(summary.summary.copy_summary.files_copied, 1);
7173 Ok(())
7174 }
7175
7176 #[tokio::test]
7178 async fn hinted_update_directory_classifies_while_pool_is_saturated()
7179 -> Result<(), anyhow::Error> {
7180 let root = testutils::create_temp_dir().await?;
7181 let src = root.join("src");
7182 let update = root.join("update");
7183 let dst = root.join("dst");
7184 tokio::fs::create_dir(&src).await?;
7185 tokio::fs::create_dir(&update).await?;
7186 tokio::fs::create_dir(update.join("dir")).await?;
7187 let admission = testutils::AdmissionLimit::new().await;
7188 admission.set_files_in_flight(1);
7189 let held = throttle::open_file_permit().await;
7190 let src_dir =
7191 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7192 let update_dir =
7193 Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
7194 let mut settings = common_settings(false, false);
7195 settings.dry_run = Some(crate::config::DryRunMode::Brief);
7196 settings.copy_settings.dry_run = settings.dry_run;
7197 let operation = crate::task_scope::scope_tasks(link_dir_contents(
7198 &PROGRESS,
7199 &src_dir,
7200 update_dir.meta().await?,
7201 Some(&update_dir),
7202 None,
7203 None,
7204 std::ffi::OsStr::new("dst"),
7205 &src,
7206 &dst,
7207 Some(&update),
7208 std::path::Path::new(""),
7209 &src,
7210 &dst,
7211 false,
7212 false,
7213 None,
7214 &settings,
7215 Summary::default(),
7216 SourceEntries::Live,
7217 UpdateEntries::Live,
7218 None,
7219 copy::DestinationContext::new(&dst),
7220 ));
7221 let result = admission
7222 .run_with_timeout(std::time::Duration::from_secs(1), operation)
7223 .await;
7224 drop(held);
7225 let summary =
7226 result.context("hinted update directory waited for delegated copy admission")??;
7227 assert_eq!(summary.copy_summary.directories_created, 1);
7228 Ok(())
7229 }
7230
7231 #[tokio::test]
7235 async fn filtered_public_root_waits_for_admission_before_setup() -> Result<(), anyhow::Error>
7236 {
7237 let root = testutils::create_temp_dir().await?;
7238 let src = root.join("src");
7239 let dst = root.join("dst");
7240 tokio::fs::write(&src, b"x").await?;
7241 let mut filter = crate::filter::FilterSettings::new();
7242 filter.add_exclude("src")?;
7243 let mut settings = common_settings(false, false);
7244 settings.filter = Some(filter.clone());
7245 settings.copy_settings.filter = Some(filter);
7246 let admission = testutils::AdmissionLimit::new().await;
7247 admission.set_files_in_flight(1);
7248 let stat_resource =
7249 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7250 admission.set_max_ops_in_flight(stat_resource, 1);
7251 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7252 let operation = link(&PROGRESS, &root, &src, &dst, &None, &settings, false);
7253 tokio::pin!(operation);
7254 let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
7255 let mut second_permit = Box::pin(throttle::open_file_permit());
7256 let setup_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
7257 drop(second_permit);
7258 drop(held_stat);
7259 let result = admission
7260 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7261 .await;
7262 assert!(
7263 stopped_at_stat_gate,
7264 "rlink root did not reach the held stat gate"
7265 );
7266 let summary =
7267 result.context("rlink root did not resume after stat capacity was released")??;
7268 assert!(
7269 !setup_bypassed_admission,
7270 "rlink performed root setup before open-file admission"
7271 );
7272 assert_eq!(summary.copy_summary.files_skipped, 1);
7273 Ok(())
7274 }
7275
7276 #[tokio::test]
7279 async fn root_acquires_capacity_before_classification() -> Result<(), anyhow::Error> {
7280 let root = testutils::create_temp_dir().await?;
7281 let src_path = root.join("src");
7282 let dst_path = root.join("dst");
7283 tokio::fs::write(&src_path, b"x").await?;
7284 let admission = testutils::AdmissionLimit::new().await;
7285 let src_parent = Arc::new(
7286 Dir::open_parent_dir(&root, congestion::Side::Source)
7287 .await?
7288 .into_tree(),
7289 );
7290 let mut settings = common_settings(false, false);
7291 settings.dry_run = Some(crate::config::DryRunMode::Brief);
7292 settings.copy_settings.dry_run = settings.dry_run;
7293 admission.set_files_in_flight(1);
7294 let stat_resource =
7295 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7296 admission.set_max_ops_in_flight(stat_resource, 1);
7297 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7298 let operation = link_internal(
7299 &PROGRESS,
7300 &src_parent,
7301 None,
7302 None,
7303 std::ffi::OsStr::new("src"),
7304 &src_path,
7305 &dst_path,
7306 None,
7307 std::path::Path::new(""),
7308 UpdateRootRequirement::Optional,
7309 &settings,
7310 false,
7311 EntryAdmission::RootOrDelegated.into(),
7312 copy::DestinationContext::new(&dst_path),
7313 );
7314 tokio::pin!(operation);
7315 let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
7316 let mut second_permit = Box::pin(throttle::open_file_permit());
7317 let classification_bypassed_admission =
7318 futures::poll!(second_permit.as_mut()).is_ready();
7319 drop(second_permit);
7320 drop(held_stat);
7321 let result = admission
7322 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7323 .await;
7324 assert!(
7325 stopped_at_stat_gate,
7326 "rlink root did not reach the held stat gate"
7327 );
7328 assert!(
7329 !classification_bypassed_admission,
7330 "rlink reached fd-based classification before open-file admission"
7331 );
7332 let summary = result.context(
7333 "rlink root did not resume after classification capacity was released",
7334 )??;
7335 assert_eq!(summary.summary.hard_links_created, 1);
7336 Ok(())
7337 }
7338
7339 #[tokio::test]
7342 async fn hard_link_holds_open_file_capacity_until_link_finishes()
7343 -> Result<(), anyhow::Error> {
7344 let root = testutils::create_temp_dir().await?;
7345 let src_root = root.join("src");
7346 let dst_root = root.join("dst");
7347 tokio::fs::create_dir(&src_root).await?;
7348 tokio::fs::create_dir(&dst_root).await?;
7349 tokio::fs::write(src_root.join("entry"), b"x").await?;
7350 let src_parent =
7351 Arc::new(Dir::open_root_dir(&src_root, false, congestion::Side::Source).await?);
7352 let dst_parent = Arc::new(
7353 Dir::open_root_dir(&dst_root, false, congestion::Side::Destination).await?,
7354 );
7355 let admission = testutils::AdmissionLimit::new().await;
7356 admission.set_files_in_flight(1);
7357 let permit = Some(LeafPermit::OpenFile(throttle::open_file_permit().await));
7358 let hard_link_resource = throttle::Resource::meta(
7359 throttle::Side::Destination,
7360 throttle::MetadataOp::HardLink,
7361 );
7362 admission.set_max_ops_in_flight(hard_link_resource, 1);
7363 let held_hard_link = throttle::ops_in_flight_permit(hard_link_resource).await;
7364 let dst_entry = dst_root.join("entry");
7365 let task_dst_entry = dst_entry.clone();
7366 let mut task = tokio::spawn(async move {
7367 link_internal(
7368 &PROGRESS,
7369 &src_parent,
7370 None,
7371 Some(&dst_parent),
7372 std::ffi::OsStr::new("entry"),
7373 &src_root.join("entry"),
7374 &task_dst_entry,
7375 None,
7376 std::path::Path::new(""),
7377 UpdateRootRequirement::Optional,
7378 &common_settings(false, false),
7379 true,
7380 EntryAdmission::from(permit).into(),
7381 copy::DestinationContext::new(&task_dst_entry),
7382 )
7383 .await
7384 });
7385 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
7386 let second_permit = tokio::time::timeout(
7387 std::time::Duration::from_millis(500),
7388 throttle::open_file_permit(),
7389 )
7390 .await;
7391 let released_before_link_finished = second_permit.is_ok();
7392 drop(second_permit);
7393 drop(held_hard_link);
7394 let task_result = admission
7395 .run_with_timeout(std::time::Duration::from_secs(20), &mut task)
7396 .await
7397 .context("hard link did not resume after metadata capacity was released")?;
7398 let summary = task_result?.map_err(|error| error.source)?;
7399 assert!(
7400 !released_before_link_finished,
7401 "hard-link work released its open-file permit before linkat completed"
7402 );
7403 assert_eq!(summary.summary.hard_links_created, 1);
7404 assert!(dst_entry.exists());
7405 Ok(())
7406 }
7407
7408 #[tokio::test]
7411 #[traced_test]
7412 async fn deep_tree_no_deadlock_under_files_in_flight_saturation()
7413 -> Result<(), anyhow::Error> {
7414 let tmp_dir = testutils::create_temp_dir().await?;
7415 let src = tmp_dir.join("src");
7416 let dst = tmp_dir.join("dst");
7417 let depth = 20;
7418 let files_per_level = 5;
7419 let limit = 1;
7420 let mut dir = src.clone();
7422 for level in 0..depth {
7423 tokio::fs::create_dir_all(&dir).await?;
7424 for f in 0..files_per_level {
7425 tokio::fs::write(
7426 dir.join(format!("f{}_{}.txt", level, f)),
7427 format!("L{}F{}", level, f),
7428 )
7429 .await?;
7430 }
7431 dir = dir.join(format!("d{}", level));
7432 }
7433 let admission = testutils::AdmissionLimit::new().await;
7434 admission.set_files_in_flight(limit);
7435 let summary = admission
7436 .run_with_timeout(
7437 std::time::Duration::from_secs(30),
7438 link(
7439 &PROGRESS,
7440 tmp_dir.as_path(),
7441 &src,
7442 &dst,
7443 &None,
7444 &common_settings(false, false),
7445 false,
7446 ),
7447 )
7448 .await
7449 .context("link timed out — possible deadlock")?
7450 .context("link failed")?;
7451 assert_eq!(summary.hard_links_created, depth * files_per_level);
7452 assert_eq!(summary.copy_summary.directories_created, depth);
7453 let mut check_dir = dst.clone();
7455 for level in 0..depth {
7456 let content =
7457 tokio::fs::read_to_string(check_dir.join(format!("f{}_0.txt", level))).await?;
7458 assert_eq!(content, format!("L{}F0", level));
7459 check_dir = check_dir.join(format!("d{}", level));
7460 }
7461 Ok(())
7462 }
7463
7464 #[tokio::test]
7468 #[traced_test]
7469 async fn matching_dual_directory_chain_releases_admission_before_recursion()
7470 -> Result<(), anyhow::Error> {
7471 let tmp_dir = testutils::create_temp_dir().await?;
7472 let src = tmp_dir.join("src");
7473 let update = tmp_dir.join("update");
7474 let dst = tmp_dir.join("dst");
7475 tokio::fs::create_dir(&src).await?;
7476 tokio::fs::create_dir(&update).await?;
7477 let depth = 12;
7478 let mut src_dir = src.clone();
7479 let mut update_dir = update.clone();
7480 for level in 0..depth {
7481 let name = format!("d{level}");
7482 src_dir.push(&name);
7483 update_dir.push(&name);
7484 tokio::fs::create_dir(&src_dir).await?;
7485 tokio::fs::create_dir(&update_dir).await?;
7486 }
7487 let admission = testutils::AdmissionLimit::new().await;
7488 admission.set_files_in_flight(1);
7489 let summary = admission
7490 .run_with_timeout(
7491 std::time::Duration::from_secs(5),
7492 link(
7493 &PROGRESS,
7494 tmp_dir.as_path(),
7495 &src,
7496 &dst,
7497 &Some(update),
7498 &common_settings(false, false),
7499 false,
7500 ),
7501 )
7502 .await
7503 .context("link timed out — direct dual-directory recursion retained admission")?
7504 .context("link failed")?;
7505 assert_eq!(summary.copy_summary.directories_created, depth + 1);
7506 assert!(
7507 src_dir
7508 .strip_prefix(&src)
7509 .is_ok_and(|tail| dst.join(tail).is_dir())
7510 );
7511 Ok(())
7512 }
7513
7514 #[tokio::test]
7524 #[traced_test]
7525 async fn type_changed_directory_releases_admission_before_recursion()
7526 -> Result<(), anyhow::Error> {
7527 let tmp_dir = testutils::create_temp_dir().await?;
7528 let src = tmp_dir.join("src");
7529 let update = tmp_dir.join("update");
7530 let dst = tmp_dir.join("dst");
7531 tokio::fs::create_dir(&src).await?;
7532 tokio::fs::create_dir(&update).await?;
7533 let n = 8;
7534 for i in 0..n {
7538 tokio::fs::write(src.join(format!("e{}", i)), format!("src-{}", i)).await?;
7539 let upd_subdir = update.join(format!("e{}", i));
7540 tokio::fs::create_dir(&upd_subdir).await?;
7541 for j in 0..3 {
7542 tokio::fs::write(
7543 upd_subdir.join(format!("inner_{}.txt", j)),
7544 format!("upd-{}-{}", i, j),
7545 )
7546 .await?;
7547 }
7548 }
7549 let admission = testutils::AdmissionLimit::new().await;
7551 admission.set_files_in_flight(2);
7552 let summary = admission
7553 .run_with_timeout(
7554 std::time::Duration::from_secs(30),
7555 link(
7556 &PROGRESS,
7557 tmp_dir.as_path(),
7558 &src,
7559 &dst,
7560 &Some(update.clone()),
7561 &common_settings(false, false),
7562 false,
7563 ),
7564 )
7565 .await
7566 .context(
7567 "link timed out — delegated admission was retained during directory descent",
7568 )?
7569 .context("link failed")?;
7570 assert_eq!(summary.copy_summary.directories_created, n + 1); assert_eq!(summary.copy_summary.files_copied, n * 3);
7574 for i in 0..n {
7576 for j in 0..3 {
7577 let content =
7578 tokio::fs::read_to_string(dst.join(format!("e{}/inner_{}.txt", i, j)))
7579 .await?;
7580 assert_eq!(content, format!("upd-{}-{}", i, j));
7581 }
7582 }
7583 Ok(())
7584 }
7585
7586 async fn check_update_read_error(
7587 fail_early: bool,
7588 child_error: bool,
7589 ) -> anyhow::Result<()> {
7590 use std::os::unix::fs::MetadataExt as _;
7591
7592 let root = testutils::create_temp_dir().await?;
7593 let src = root.join("src");
7594 let update = root.join("update");
7595 let dst = root.join("dst");
7596 for path in [&src, &update, &dst] {
7597 tokio::fs::create_dir(path).await?;
7598 }
7599 tokio::fs::write(src.join("first"), b"first").await?;
7600 let (second, _socket) = if child_error {
7601 tokio::fs::create_dir(src.join("sub")).await?;
7602 tokio::fs::write(src.join("sub/good"), b"good").await?;
7603 (
7604 "sub/good",
7605 Some(std::os::unix::net::UnixListener::bind(
7606 src.join("sub/bad.sock"),
7607 )?),
7608 )
7609 } else {
7610 tokio::fs::write(src.join("second"), b"second").await?;
7611 ("second", None)
7612 };
7613 tokio::fs::write(dst.join("must-survive"), b"extraneous").await?;
7614 tokio::fs::set_permissions(&update, std::fs::Permissions::from_mode(0o751)).await?;
7615 tokio::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o700)).await?;
7616 let admission = testutils::AdmissionLimit::new().await;
7617 admission.set_files_in_flight(2);
7618 let resource = throttle::Resource::meta(
7619 throttle::Side::Destination,
7620 throttle::MetadataOp::HardLink,
7621 );
7622 admission.set_max_ops_in_flight(resource, 1);
7623 let held_link = throttle::ops_in_flight_permit(resource).await;
7624 let src_dir =
7625 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7626 let update_dir =
7627 Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
7628 let dst_dir =
7629 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7630 let dst_parent =
7631 Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7632 let mut settings = common_settings(false, false);
7633 settings.copy_settings.fail_early = fail_early;
7634 settings.copy_settings.delete = Some(copy::DeleteSettings {
7635 delete_excluded: false,
7636 });
7637 let progress = Box::leak(Box::new(progress::Progress::new()));
7638 let (trigger_error, read_error) = tokio::sync::oneshot::channel();
7639 let operation = crate::task_scope::scope_tasks(link_dir_contents(
7640 progress,
7641 &src_dir,
7642 update_dir.meta().await?,
7643 Some(&update_dir),
7644 Some(&dst_dir),
7645 Some(&dst_parent),
7646 std::ffi::OsStr::new("dst"),
7647 &src,
7648 &dst,
7649 Some(&update),
7650 std::path::Path::new(""),
7651 &src,
7652 &dst,
7653 true,
7654 false,
7655 None,
7656 &settings,
7657 Summary {
7658 copy_summary: copy::Summary {
7659 directories_created: 1,
7660 ..Default::default()
7661 },
7662 ..Default::default()
7663 },
7664 SourceEntries::Injected(vec![
7665 (std::ffi::OsString::from("first"), Some(EntryKind::File)),
7666 if child_error {
7667 (std::ffi::OsString::from("sub"), Some(EntryKind::Dir))
7668 } else {
7669 (std::ffi::OsString::from("second"), Some(EntryKind::File))
7670 },
7671 ]),
7672 UpdateEntries::InjectedReadError(read_error),
7673 None,
7674 copy::DestinationContext::new(&dst),
7675 ));
7676 tokio::pin!(operation);
7677 let started = tokio::time::timeout(std::time::Duration::from_secs(5), async {
7680 loop {
7681 assert!(futures::poll!(operation.as_mut()).is_pending());
7682 let status = progress.ops.get();
7683 if status.started >= if child_error { 3 } else { 2 }
7684 && available_open_file_capacity(2) == 0
7685 {
7686 break;
7687 }
7688 tokio::task::yield_now().await;
7689 }
7690 })
7691 .await;
7692 trigger_error
7693 .send(std::io::Error::from_raw_os_error(libc::EIO))
7694 .unwrap();
7695 let gated_result = tokio::time::timeout(
7696 std::time::Duration::from_millis(if fail_early { 1000 } else { 100 }),
7697 operation.as_mut(),
7698 )
7699 .await;
7700 let returned_while_gated = gated_result.is_ok();
7701 drop(held_link);
7702 let result = match gated_result {
7703 Ok(result) => result,
7704 Err(_) => {
7705 admission
7706 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
7707 .await?
7708 }
7709 };
7710 reacquire_all_open_file_capacity(&admission, 2).await?;
7711 started.context("source workers did not start while update enumeration was pending")?;
7712 assert_eq!(
7713 returned_while_gated, fail_early,
7714 "only fail-early may cancel pending source workers"
7715 );
7716 let error = result.expect_err("update enumeration must fail");
7717 let message = format!("{:#}", error.source);
7718 assert!(
7719 message.contains(&std::io::Error::from_raw_os_error(libc::EIO).to_string()),
7720 "{message}"
7721 );
7722 if !child_error {
7723 assert!(message.contains(update.to_str().unwrap()), "{message}");
7724 assert_eq!(
7725 error
7726 .source
7727 .downcast_ref::<std::io::Error>()
7728 .unwrap()
7729 .raw_os_error(),
7730 Some(libc::EIO)
7731 );
7732 }
7733 assert_eq!(
7734 error.summary.hard_links_created,
7735 if fail_early { 0 } else { 2 }
7736 );
7737 assert_eq!(
7738 error.summary.copy_summary.directories_created,
7739 if child_error { 2 } else { 1 }
7740 );
7741 assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 0);
7742 assert_eq!(
7743 tokio::fs::read(dst.join("must-survive")).await?,
7744 b"extraneous"
7745 );
7746 assert_eq!(
7747 tokio::fs::metadata(&dst).await?.mode() & 0o777,
7748 if fail_early { 0o700 } else { 0o751 }
7749 );
7750 for name in ["first", second] {
7751 if fail_early {
7752 assert!(!dst.join(name).exists());
7753 } else {
7754 let source = tokio::fs::metadata(src.join(name)).await?;
7755 let destination = tokio::fs::metadata(dst.join(name)).await?;
7756 assert_eq!(
7757 (source.dev(), source.ino()),
7758 (destination.dev(), destination.ino())
7759 );
7760 }
7761 }
7762 if child_error {
7763 assert!(message.contains("unsupported"), "{message}");
7764 }
7765 Ok(())
7766 }
7767
7768 #[tokio::test(flavor = "current_thread")]
7769 async fn update_read_error_drains_pending_source_workers() -> anyhow::Result<()> {
7770 check_update_read_error(false, false).await
7771 }
7772
7773 #[tokio::test(flavor = "current_thread")]
7774 async fn update_read_error_folds_failed_child_partial_summary() -> anyhow::Result<()> {
7775 check_update_read_error(false, true).await
7776 }
7777
7778 #[tokio::test(flavor = "current_thread")]
7779 async fn update_read_error_fail_early_cancels_pending_source_workers() -> anyhow::Result<()>
7780 {
7781 check_update_read_error(true, false).await
7782 }
7783
7784 #[tokio::test]
7785 async fn source_read_error_finalizes_without_dispatching_update_entries()
7786 -> anyhow::Result<()> {
7787 use std::os::unix::fs::MetadataExt as _;
7788
7789 for with_update in [false, true] {
7790 for fail_early in [false, true] {
7791 let root = testutils::create_temp_dir().await?;
7792 let src = root.join("src");
7793 let update = root.join("update");
7794 let dst = root.join("dst");
7795 for path in [&src, &update, &dst] {
7796 tokio::fs::create_dir(path).await?;
7797 }
7798 tokio::fs::write(src.join("same"), b"source").await?;
7799 tokio::fs::write(update.join("same"), b"different update").await?;
7800 tokio::fs::write(update.join("update-only"), b"update-only").await?;
7801 tokio::fs::write(dst.join("must-survive"), b"extraneous").await?;
7802 for (path, mode) in [(&src, 0o750), (&update, 0o751), (&dst, 0o700)] {
7803 tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
7804 .await?;
7805 }
7806 let src_dir =
7807 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7808 let update_dir = Arc::new(
7809 Dir::open_root_dir(&update, false, congestion::Side::Source).await?,
7810 );
7811 let dst_dir = Arc::new(
7812 Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?,
7813 );
7814 let dst_parent = Arc::new(
7815 Dir::open_root_dir(&root, false, congestion::Side::Destination).await?,
7816 );
7817 let mut settings = common_settings(false, false);
7818 settings.copy_settings.fail_early = fail_early;
7819 settings.copy_settings.delete = Some(copy::DeleteSettings {
7820 delete_excluded: false,
7821 });
7822 let error = crate::task_scope::scope_tasks(link_dir_contents(
7823 &PROGRESS,
7824 &src_dir,
7825 (if with_update { &update_dir } else { &src_dir })
7826 .meta()
7827 .await?,
7828 with_update.then_some(&update_dir),
7829 Some(&dst_dir),
7830 Some(&dst_parent),
7831 std::ffi::OsStr::new("dst"),
7832 &src,
7833 &dst,
7834 with_update.then_some(update.as_path()),
7835 std::path::Path::new(""),
7836 &src,
7837 &dst,
7838 true,
7839 false,
7840 None,
7841 &settings,
7842 Summary {
7843 copy_summary: copy::Summary {
7844 directories_created: 1,
7845 ..Default::default()
7846 },
7847 ..Default::default()
7848 },
7849 SourceEntries::InjectedReadError(std::io::Error::from_raw_os_error(
7850 libc::EIO,
7851 )),
7852 UpdateEntries::Live,
7853 None,
7854 copy::DestinationContext::new(&dst),
7855 ))
7856 .await
7857 .expect_err("source enumeration must fail");
7858 assert!(format!("{:#}", error.source).contains(src.to_str().unwrap()));
7859 assert_eq!(
7860 error
7861 .source
7862 .downcast_ref::<std::io::Error>()
7863 .unwrap()
7864 .raw_os_error(),
7865 Some(libc::EIO)
7866 );
7867 assert_eq!(error.summary.copy_summary.directories_created, 1);
7868 assert_eq!(error.summary.hard_links_created, 0);
7869 assert_eq!(error.summary.copy_summary.files_copied, 0);
7870 assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 0);
7871 assert!(!dst.join("same").exists());
7872 assert!(!dst.join("update-only").exists());
7873 assert_eq!(
7874 tokio::fs::read(dst.join("must-survive")).await?,
7875 b"extraneous"
7876 );
7877 assert_eq!(
7878 tokio::fs::metadata(&dst).await?.mode() & 0o777,
7879 if fail_early {
7880 0o700
7881 } else if with_update {
7882 0o751
7883 } else {
7884 0o750
7885 }
7886 );
7887 }
7888 }
7889 Ok(())
7890 }
7891
7892 #[tokio::test]
7893 async fn source_read_error_finishes_empty_directory_cleanup() -> anyhow::Result<()> {
7894 for dry_run in [false, true] {
7895 let root = testutils::create_temp_dir().await?;
7896 let src = root.join("src");
7897 let dst = root.join("dst");
7898 let dst_sub = dst.join("sub");
7899 tokio::fs::create_dir(&src).await?;
7900 tokio::fs::create_dir(&dst).await?;
7901 if !dry_run {
7902 tokio::fs::create_dir(&dst_sub).await?;
7903 }
7904 let src_dir =
7905 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7906 let dst_parent =
7907 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7908 let dst_dir = if dry_run {
7909 None
7910 } else {
7911 Some(Arc::new(
7912 Dir::open_root_dir(&dst_sub, false, congestion::Side::Destination).await?,
7913 ))
7914 };
7915 let mut settings = common_settings(false, false);
7916 let mut filter = crate::filter::FilterSettings::new();
7917 filter.add_include("*.match")?;
7918 settings.filter = Some(filter.clone());
7919 settings.copy_settings.filter = Some(filter);
7920 settings.dry_run = dry_run.then_some(crate::config::DryRunMode::Brief);
7921 settings.copy_settings.dry_run = settings.dry_run;
7922 let error = crate::task_scope::scope_tasks(link_dir_contents(
7923 &PROGRESS,
7924 &src_dir,
7925 src_dir.meta().await?,
7926 None,
7927 dst_dir.as_ref(),
7928 (!dry_run).then_some(&dst_parent),
7929 std::ffi::OsStr::new("sub"),
7930 &src,
7931 &dst,
7932 None,
7933 std::path::Path::new("sub"),
7934 &src,
7935 &dst_sub,
7936 true,
7937 true,
7938 None,
7939 &settings,
7940 Summary {
7941 copy_summary: copy::Summary {
7942 directories_created: 1,
7943 ..Default::default()
7944 },
7945 ..Default::default()
7946 },
7947 SourceEntries::InjectedReadError(std::io::Error::from_raw_os_error(libc::EIO)),
7948 UpdateEntries::Live,
7949 None,
7950 copy::DestinationContext::new(&dst),
7951 ))
7952 .await
7953 .expect_err("cleanup must preserve the read error");
7954 assert_eq!(
7955 error
7956 .source
7957 .downcast_ref::<std::io::Error>()
7958 .unwrap()
7959 .raw_os_error(),
7960 Some(libc::EIO)
7961 );
7962 assert_eq!(error.summary.copy_summary.directories_created, 0);
7963 assert!(!dst_sub.exists());
7964 }
7965 Ok(())
7966 }
7967
7968 #[tokio::test(flavor = "current_thread")]
7971 async fn source_fail_early_reaps_error_while_later_admission_is_saturated()
7972 -> Result<(), anyhow::Error> {
7973 let root = testutils::create_temp_dir().await?;
7974 let src = root.join("src");
7975 let dst = root.join("dst");
7976 tokio::fs::create_dir(&src).await?;
7977 tokio::fs::create_dir(&dst).await?;
7978 tokio::fs::write(src.join("vanished"), b"vanished").await?;
7979 tokio::fs::symlink("target-a", src.join("blocked-a")).await?;
7980 tokio::fs::symlink("target-b", src.join("blocked-b")).await?;
7981 tokio::fs::write(src.join("later"), b"later").await?;
7982 tokio::fs::write(src.join("uninjected"), b"uninjected").await?;
7983 let admission = testutils::AdmissionLimit::new().await;
7984 admission.set_files_in_flight(2);
7985 let stat_resource =
7986 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
7987 admission.set_max_ops_in_flight(stat_resource, 1);
7988 let readlink_resource =
7989 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::ReadLink);
7990 admission.set_max_ops_in_flight(readlink_resource, 1);
7991 let src_dir =
7992 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
7993 let dst_dir =
7994 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
7995 let dst_parent =
7996 Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
7997 let preserve_meta = src_dir.meta().await?;
7998 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
7999 let mut held_readlink = Some(throttle::ops_in_flight_permit(readlink_resource).await);
8000 let mut filter = crate::filter::FilterSettings::new();
8001 filter.add_exclude("never/")?;
8002 let mut settings = common_settings(false, false);
8003 settings.filter = Some(filter.clone());
8004 settings.copy_settings.filter = Some(filter);
8005 settings.copy_settings.fail_early = true;
8006 let operation = crate::task_scope::scope_tasks(link_dir_contents(
8007 &PROGRESS,
8008 &src_dir,
8009 preserve_meta,
8010 None,
8011 Some(&dst_dir),
8012 Some(&dst_parent),
8013 std::ffi::OsStr::new("dst"),
8014 &src,
8015 &dst,
8016 None,
8017 std::path::Path::new(""),
8018 &src,
8019 &dst,
8020 false,
8021 false,
8022 None,
8023 &settings,
8024 Summary::default(),
8025 SourceEntries::Injected(vec![
8026 (std::ffi::OsString::from("vanished"), Some(EntryKind::File)),
8027 (
8028 std::ffi::OsString::from("blocked-a"),
8029 Some(EntryKind::Symlink),
8030 ),
8031 (
8032 std::ffi::OsString::from("blocked-b"),
8033 Some(EntryKind::Symlink),
8034 ),
8035 (std::ffi::OsString::from("later"), Some(EntryKind::File)),
8036 ]),
8037 UpdateEntries::Live,
8038 None,
8039 copy::DestinationContext::new(&dst),
8040 ));
8041 tokio::pin!(operation);
8042 let mut completed_while_gated = None;
8043 let saturated = tokio::time::timeout(std::time::Duration::from_secs(5), async {
8044 loop {
8045 if let std::task::Poll::Ready(output) = futures::poll!(operation.as_mut()) {
8046 completed_while_gated = Some(output);
8047 return;
8048 }
8049 if available_open_file_capacity(2) == 0 {
8050 return;
8051 }
8052 tokio::task::yield_now().await;
8053 }
8054 })
8055 .await;
8056 let remove_result = tokio::fs::remove_file(src.join("vanished")).await;
8057 drop(held_stat);
8058 if let Some(output) = completed_while_gated {
8059 drop(held_readlink.take());
8060 reacquire_all_open_file_capacity(&admission, 2).await?;
8061 return Err(anyhow!(
8062 "source link completed before its gated workers saturated admission: {:?}",
8063 output.err().map(|error| format!("{:#}", error.source))
8064 ));
8065 }
8066 if let Err(error) = saturated {
8067 drop(held_readlink.take());
8068 let _ = admission
8069 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
8070 .await;
8071 reacquire_all_open_file_capacity(&admission, 2).await?;
8072 return Err(error).context("source workers did not saturate open-file admission");
8073 }
8074 if let Err(error) = remove_result {
8075 drop(held_readlink.take());
8076 let _ = admission
8077 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
8078 .await;
8079 reacquire_all_open_file_capacity(&admission, 2).await?;
8080 return Err(error).context("failed to remove the injected source entry");
8081 }
8082 let result =
8083 tokio::time::timeout(std::time::Duration::from_secs(1), operation.as_mut()).await;
8084 drop(held_readlink.take());
8085 if result.is_err() {
8086 let _ = admission
8087 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
8088 .await;
8089 }
8090 reacquire_all_open_file_capacity(&admission, 2).await?;
8091 let error = result
8092 .context("fail-early source error was not reaped during admission")?
8093 .expect_err("the vanished source entry must fail the link");
8094 assert!(format!("{:#}", error.source).contains("vanished"));
8095 assert!(!dst.join("later").exists());
8096 assert!(!dst.join("uninjected").exists());
8097 Ok(())
8098 }
8099
8100 #[tokio::test(flavor = "current_thread")]
8103 async fn source_error_keeps_going_without_pruning_partial_collection()
8104 -> Result<(), anyhow::Error> {
8105 let root = testutils::create_temp_dir().await?;
8106 let src = root.join("src");
8107 let dst = root.join("dst");
8108 tokio::fs::create_dir(&src).await?;
8109 tokio::fs::create_dir(&dst).await?;
8110 tokio::fs::write(dst.join("must-survive"), b"extraneous").await?;
8111 tokio::fs::write(src.join("first"), b"first").await?;
8112 tokio::fs::write(src.join("last"), b"last").await?;
8113 tokio::fs::write(src.join("uninjected"), b"uninjected").await?;
8114 let admission = testutils::AdmissionLimit::new().await;
8115 admission.set_files_in_flight(3);
8116 let src_dir =
8117 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
8118 let dst_dir =
8119 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
8120 let dst_parent =
8121 Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
8122 let mut filter = crate::filter::FilterSettings::new();
8123 filter.add_exclude("never/")?;
8124 let mut settings = common_settings(false, false);
8125 settings.copy_settings.delete = Some(copy::DeleteSettings {
8126 delete_excluded: false,
8127 });
8128 settings.filter = Some(filter.clone());
8129 settings.copy_settings.filter = Some(filter);
8130 let operation = crate::task_scope::scope_tasks(link_dir_contents(
8131 &PROGRESS,
8132 &src_dir,
8133 src_dir.meta().await?,
8134 None,
8135 Some(&dst_dir),
8136 Some(&dst_parent),
8137 std::ffi::OsStr::new("dst"),
8138 &src,
8139 &dst,
8140 None,
8141 std::path::Path::new(""),
8142 &src,
8143 &dst,
8144 false,
8145 false,
8146 None,
8147 &settings,
8148 Summary::default(),
8149 SourceEntries::Injected(vec![
8150 (std::ffi::OsString::from("first"), None),
8151 (std::ffi::OsString::from("vanished"), None),
8152 (std::ffi::OsString::from("last"), None),
8153 ]),
8154 UpdateEntries::Live,
8155 None,
8156 copy::DestinationContext::new(&dst),
8157 ));
8158 let result = admission
8159 .run_with_timeout(std::time::Duration::from_secs(20), operation)
8160 .await;
8161 reacquire_all_open_file_capacity(&admission, 3).await?;
8162 let error = result
8163 .context("keep-going unknown-source link did not terminate")?
8164 .expect_err("the injected vanished source must fail");
8165 assert_eq!(error.summary.hard_links_created, 2);
8166 assert_eq!(tokio::fs::read(dst.join("first")).await?, b"first");
8167 assert_eq!(tokio::fs::read(dst.join("last")).await?, b"last");
8168 assert!(!dst.join("uninjected").exists());
8169 assert_eq!(
8170 tokio::fs::read(dst.join("must-survive")).await?,
8171 b"extraneous"
8172 );
8173 assert_eq!(error.summary.copy_summary.rm_summary.files_removed, 0);
8174 Ok(())
8175 }
8176
8177 #[tokio::test]
8180 async fn source_unknown_excluded_directory_uses_directory_skip_accounting()
8181 -> Result<(), anyhow::Error> {
8182 let root = testutils::create_temp_dir().await?;
8183 let src = root.join("src");
8184 let dst = root.join("dst");
8185 tokio::fs::create_dir(&src).await?;
8186 tokio::fs::create_dir(&dst).await?;
8187 tokio::fs::create_dir(src.join("node")).await?;
8188 tokio::fs::write(src.join("uninjected"), b"uninjected").await?;
8189 let src_dir =
8190 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
8191 let dst_dir =
8192 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
8193 let dst_parent =
8194 Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
8195 let mut filter = crate::filter::FilterSettings::new();
8196 filter.add_exclude("node/")?;
8197 let mut settings = common_settings(false, false);
8198 settings.filter = Some(filter.clone());
8199 settings.copy_settings.filter = Some(filter);
8200 let summary = crate::task_scope::scope_tasks(link_dir_contents(
8201 &PROGRESS,
8202 &src_dir,
8203 src_dir.meta().await?,
8204 None,
8205 Some(&dst_dir),
8206 Some(&dst_parent),
8207 std::ffi::OsStr::new("dst"),
8208 &src,
8209 &dst,
8210 None,
8211 std::path::Path::new(""),
8212 &src,
8213 &dst,
8214 false,
8215 false,
8216 None,
8217 &settings,
8218 Summary::default(),
8219 SourceEntries::Injected(vec![(std::ffi::OsString::from("node"), None)]),
8220 UpdateEntries::Live,
8221 None,
8222 copy::DestinationContext::new(&dst),
8223 ))
8224 .await?;
8225 assert_eq!(summary.copy_summary.directories_skipped, 1);
8226 assert_eq!(summary.copy_summary.files_skipped, 0);
8227 assert!(!dst.join("node").exists());
8228 assert!(!dst.join("uninjected").exists());
8229 Ok(())
8230 }
8231
8232 #[tokio::test(flavor = "current_thread")]
8235 async fn source_unknown_workers_classify_concurrently() -> Result<(), anyhow::Error> {
8236 let root = testutils::create_temp_dir().await?;
8237 let src = root.join("src");
8238 let dst = root.join("dst");
8239 tokio::fs::create_dir(&src).await?;
8240 tokio::fs::create_dir(&dst).await?;
8241 tokio::fs::write(src.join("first"), b"first").await?;
8242 tokio::fs::write(src.join("second"), b"second").await?;
8243 tokio::fs::write(src.join("uninjected"), b"uninjected").await?;
8244 let admission = testutils::AdmissionLimit::new().await;
8245 admission.set_files_in_flight(2);
8246 let stat_resource =
8247 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
8248 admission.set_max_ops_in_flight(stat_resource, 1);
8249 let src_dir =
8250 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
8251 let dst_dir =
8252 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
8253 let dst_parent =
8254 Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
8255 let preserve_meta = src_dir.meta().await?;
8256 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
8257 let mut filter = crate::filter::FilterSettings::new();
8258 filter.add_exclude("never/")?;
8259 let mut settings = common_settings(false, false);
8260 settings.filter = Some(filter.clone());
8261 settings.copy_settings.filter = Some(filter);
8262 let operation = crate::task_scope::scope_tasks(link_dir_contents(
8263 &PROGRESS,
8264 &src_dir,
8265 preserve_meta,
8266 None,
8267 Some(&dst_dir),
8268 Some(&dst_parent),
8269 std::ffi::OsStr::new("dst"),
8270 &src,
8271 &dst,
8272 None,
8273 std::path::Path::new(""),
8274 &src,
8275 &dst,
8276 false,
8277 false,
8278 None,
8279 &settings,
8280 Summary::default(),
8281 SourceEntries::Injected(vec![
8282 (std::ffi::OsString::from("first"), None),
8283 (std::ffi::OsString::from("second"), None),
8284 ]),
8285 UpdateEntries::Live,
8286 None,
8287 copy::DestinationContext::new(&dst),
8288 ));
8289 tokio::pin!(operation);
8290 let mut completed_while_gated = None;
8291 let concurrent = tokio::time::timeout(std::time::Duration::from_secs(5), async {
8292 loop {
8293 if let std::task::Poll::Ready(output) = futures::poll!(operation.as_mut()) {
8294 completed_while_gated = Some(output);
8295 return;
8296 }
8297 if available_open_file_capacity(2) == 0 {
8298 return;
8299 }
8300 tokio::task::yield_now().await;
8301 }
8302 })
8303 .await;
8304 drop(held_stat);
8305 let task_result = admission
8306 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
8307 .await;
8308 reacquire_all_open_file_capacity(&admission, 2).await?;
8309 if let Some(output) = completed_while_gated {
8310 return Err(anyhow!(
8311 "unknown source link completed before gated classifications: {:?}",
8312 output.err().map(|error| format!("{:#}", error.source))
8313 ));
8314 }
8315 concurrent.context("unknown source workers did not classify concurrently")?;
8316 let summary = task_result
8317 .context("unknown source classifications did not resume after stat release")??;
8318 assert_eq!(summary.hard_links_created, 2);
8319 assert!(!dst.join("uninjected").exists());
8320 Ok(())
8321 }
8322
8323 #[tokio::test(flavor = "current_thread")]
8326 async fn update_only_workers_classify_concurrently() -> Result<(), anyhow::Error> {
8327 let root = testutils::create_temp_dir().await?;
8328 let src = root.join("src");
8329 let update = root.join("update");
8330 let dst = root.join("dst");
8331 tokio::fs::create_dir(&src).await?;
8332 tokio::fs::create_dir(&update).await?;
8333 tokio::fs::create_dir(&dst).await?;
8334 tokio::fs::write(update.join("first"), b"first").await?;
8335 tokio::fs::write(update.join("second"), b"second").await?;
8336 tokio::fs::write(update.join("uninjected"), b"uninjected").await?;
8337
8338 let admission = testutils::AdmissionLimit::new().await;
8339 admission.set_files_in_flight(2);
8340 let src_dir =
8341 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
8342 let update_dir =
8343 Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
8344 let dst_dir =
8345 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
8346 let dst_parent =
8347 Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
8348 let stat_resource =
8349 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
8350 admission.set_max_ops_in_flight(stat_resource, 1);
8351 let preserve_meta = update_dir.meta().await?;
8352 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
8353 let mut filter = crate::filter::FilterSettings::new();
8354 filter.add_exclude("never/")?;
8355 let mut settings = common_settings(false, false);
8356 settings.filter = Some(filter.clone());
8357 settings.copy_settings.filter = Some(filter);
8358 let operation = crate::task_scope::scope_tasks(link_dir_contents(
8359 &PROGRESS,
8360 &src_dir,
8361 preserve_meta,
8362 Some(&update_dir),
8363 Some(&dst_dir),
8364 Some(&dst_parent),
8365 std::ffi::OsStr::new("dst"),
8366 &src,
8367 &dst,
8368 Some(&update),
8369 std::path::Path::new(""),
8370 &src,
8371 &dst,
8372 false,
8373 false,
8374 None,
8375 &settings,
8376 Summary::default(),
8377 SourceEntries::Live,
8378 UpdateEntries::Injected(vec![
8379 (std::ffi::OsString::from("first"), Some(EntryKind::File)),
8380 (std::ffi::OsString::from("second"), Some(EntryKind::File)),
8381 ]),
8382 None,
8383 copy::DestinationContext::new(&dst),
8384 ));
8385 tokio::pin!(operation);
8386 let available_while_classifying = loop {
8387 assert!(
8388 futures::poll!(operation.as_mut()).is_pending(),
8389 "update-only link completed while exact classifications were gated"
8390 );
8391 let mut available = Vec::new();
8392 for _ in 0..2 {
8393 let mut probe = Box::pin(throttle::open_file_permit());
8394 match futures::poll!(probe.as_mut()) {
8395 std::task::Poll::Ready(permit) => available.push(permit),
8396 std::task::Poll::Pending => break,
8397 }
8398 }
8399 let count = available.len();
8400 drop(available);
8401 if count < 2 {
8402 break count;
8403 }
8404 tokio::task::yield_now().await;
8405 };
8406 drop(held_stat);
8407 assert!(
8408 available_while_classifying == 0,
8409 "the first exact update-only classification serialized its sibling"
8410 );
8411 let summary = admission
8412 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
8413 .await
8414 .context("update-only classifications did not resume after stat release")??;
8415 assert_eq!(summary.copy_summary.files_copied, 2);
8416 Ok(())
8417 }
8418
8419 #[tokio::test(flavor = "current_thread")]
8422 async fn update_only_classification_error_keeps_going_and_folds_siblings()
8423 -> Result<(), anyhow::Error> {
8424 let root = testutils::create_temp_dir().await?;
8425 let src = root.join("src");
8426 let update = root.join("update");
8427 let dst = root.join("dst");
8428 tokio::fs::create_dir(&src).await?;
8429 tokio::fs::create_dir(&update).await?;
8430 tokio::fs::create_dir(&dst).await?;
8431 for name in ["first", "middle", "last"] {
8432 tokio::fs::write(update.join(name), name.as_bytes()).await?;
8433 }
8434 tokio::fs::write(update.join("uninjected"), b"uninjected").await?;
8435
8436 let admission = testutils::AdmissionLimit::new().await;
8437 admission.set_files_in_flight(3);
8438 let src_dir =
8439 Arc::new(Dir::open_root_dir(&src, false, congestion::Side::Source).await?);
8440 let update_dir =
8441 Arc::new(Dir::open_root_dir(&update, false, congestion::Side::Source).await?);
8442 let dst_dir =
8443 Arc::new(Dir::open_root_dir(&dst, false, congestion::Side::Destination).await?);
8444 let dst_parent =
8445 Arc::new(Dir::open_root_dir(&root, false, congestion::Side::Destination).await?);
8446 let stat_resource =
8447 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
8448 admission.set_max_ops_in_flight(stat_resource, 1);
8449 let preserve_meta = update_dir.meta().await?;
8450 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
8451 let vanished = std::ffi::OsString::from("middle");
8452 let successful = [
8453 std::ffi::OsString::from("first"),
8454 std::ffi::OsString::from("last"),
8455 ];
8456 let settings = common_settings(false, false);
8457 let operation = crate::task_scope::scope_tasks(link_dir_contents(
8458 &PROGRESS,
8459 &src_dir,
8460 preserve_meta,
8461 Some(&update_dir),
8462 Some(&dst_dir),
8463 Some(&dst_parent),
8464 std::ffi::OsStr::new("dst"),
8465 &src,
8466 &dst,
8467 Some(&update),
8468 std::path::Path::new(""),
8469 &src,
8470 &dst,
8471 false,
8472 false,
8473 None,
8474 &settings,
8475 Summary::default(),
8476 SourceEntries::Live,
8477 UpdateEntries::Injected(vec![
8478 (std::ffi::OsString::from("first"), Some(EntryKind::File)),
8479 (std::ffi::OsString::from("middle"), Some(EntryKind::File)),
8480 (std::ffi::OsString::from("last"), Some(EntryKind::File)),
8481 ]),
8482 None,
8483 copy::DestinationContext::new(&dst),
8484 ));
8485 tokio::pin!(operation);
8486 loop {
8487 assert!(
8488 futures::poll!(operation.as_mut()).is_pending(),
8489 "update-only link completed while exact classifications were gated"
8490 );
8491 let mut available = Vec::new();
8492 for _ in 0..3 {
8493 let mut probe = Box::pin(throttle::open_file_permit());
8494 match futures::poll!(probe.as_mut()) {
8495 std::task::Poll::Ready(permit) => available.push(permit),
8496 std::task::Poll::Pending => break,
8497 }
8498 }
8499 let count = available.len();
8500 drop(available);
8501 if count < 3 {
8502 break;
8503 }
8504 tokio::task::yield_now().await;
8505 }
8506 tokio::fs::remove_file(update.join(&vanished)).await?;
8507 drop(held_stat);
8508 let error = admission
8509 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
8510 .await
8511 .context("keep-going update-only link did not terminate")?
8512 .expect_err("the vanished update-only entry classification must fail");
8513 assert_eq!(
8514 error.summary.copy_summary.files_copied, 2,
8515 "the combined error summary must include both successful siblings"
8516 );
8517 assert!(format!("{:#}", error.source).contains(vanished.to_string_lossy().as_ref()));
8518 for name in successful {
8519 assert_eq!(
8520 tokio::fs::read(dst.join(&name)).await?,
8521 name.as_encoded_bytes(),
8522 "successful sibling {name:?} did not materialize"
8523 );
8524 }
8525 assert!(!dst.join(vanished).exists());
8526 Ok(())
8527 }
8528
8529 #[tokio::test]
8533 async fn update_only_spawning_stops_at_open_file_capacity() -> Result<(), anyhow::Error> {
8534 let tmp_dir = testutils::create_temp_dir().await?;
8535 let src = tmp_dir.join("src");
8536 let update = tmp_dir.join("update");
8537 let dst = tmp_dir.join("dst");
8538 tokio::fs::create_dir(&src).await?;
8539 tokio::fs::create_dir(&update).await?;
8540 let n = 8;
8541 for i in 0..n {
8542 tokio::fs::symlink(format!("target-{i}"), update.join(format!("u{i}"))).await?;
8543 }
8544 let progress: &'static progress::Progress =
8545 Box::leak(Box::new(progress::Progress::new()));
8546 let admission = testutils::AdmissionLimit::new().await;
8547 admission.set_files_in_flight(1);
8548 let readlink_resource =
8549 throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::ReadLink);
8550 admission.set_max_ops_in_flight(readlink_resource, 1);
8551 let held_readlink = throttle::ops_in_flight_permit(readlink_resource).await;
8552 let mut task = tokio::spawn(async move {
8553 link(
8554 progress,
8555 &tmp_dir,
8556 &src,
8557 &dst,
8558 &Some(update),
8559 &common_settings(false, false),
8560 false,
8561 )
8562 .await
8563 });
8564 let first_worker = tokio::time::timeout(std::time::Duration::from_secs(20), async {
8565 loop {
8566 if progress.ops.get().started >= 2 {
8567 break;
8568 }
8569 tokio::task::yield_now().await;
8570 }
8571 })
8572 .await;
8573 if let Err(error) = first_worker {
8574 drop(held_readlink);
8575 admission.quiesce(&mut task).await;
8576 return Err(error).context("the first update-only worker did not start");
8577 }
8578 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
8579 let started_while_blocked = progress.ops.get().started;
8580 drop(held_readlink);
8581 let task_result = admission
8582 .run_with_timeout(std::time::Duration::from_secs(20), &mut task)
8583 .await
8584 .context("update-only copies did not resume after ReadLink was released")?;
8585 let summary = task_result?.map_err(|error| error.source)?;
8586 assert_eq!(
8587 started_while_blocked, 2,
8588 "root plus exactly one admitted update-only worker should be live"
8589 );
8590 assert_eq!(summary.copy_summary.symlinks_created, n);
8591 Ok(())
8592 }
8593
8594 #[tokio::test]
8602 #[traced_test]
8603 async fn update_only_entries_bounded_no_deadlock() -> Result<(), anyhow::Error> {
8604 let tmp_dir = testutils::create_temp_dir().await?;
8605 let src = tmp_dir.join("src");
8606 let update = tmp_dir.join("update");
8607 let dst = tmp_dir.join("dst");
8608 tokio::fs::create_dir(&src).await?;
8609 tokio::fs::create_dir(&update).await?;
8610 let n = 50;
8613 for i in 0..n {
8614 tokio::fs::write(update.join(format!("u{}", i)), format!("upd-{}", i)).await?;
8615 }
8616 let admission = testutils::AdmissionLimit::new().await;
8617 admission.set_files_in_flight(2);
8618 let summary = admission
8619 .run_with_timeout(
8620 std::time::Duration::from_secs(30),
8621 link(
8622 &PROGRESS,
8623 tmp_dir.as_path(),
8624 &src,
8625 &dst,
8626 &Some(update.clone()),
8627 &common_settings(false, false),
8628 false,
8629 ),
8630 )
8631 .await
8632 .context("link timed out — site-3 spawn loop deadlock")?
8633 .context("link failed")?;
8634 assert_eq!(summary.copy_summary.directories_created, 1);
8636 assert_eq!(summary.copy_summary.files_copied, n);
8637 for i in 0..n {
8638 let content = tokio::fs::read_to_string(dst.join(format!("u{}", i))).await?;
8639 assert_eq!(content, format!("upd-{}", i));
8640 }
8641 Ok(())
8642 }
8643
8644 #[tokio::test]
8654 #[traced_test]
8655 async fn update_only_overwrite_preexisting_dirs_no_deadlock() -> Result<(), anyhow::Error> {
8656 let tmp_dir = testutils::create_temp_dir().await?;
8657 let src = tmp_dir.join("src");
8658 let update = tmp_dir.join("update");
8659 let dst = tmp_dir.join("dst");
8660 tokio::fs::create_dir(&src).await?;
8661 tokio::fs::create_dir(&update).await?;
8662 tokio::fs::create_dir(&dst).await?;
8663 let n = 12;
8664 for i in 0..n {
8665 tokio::fs::write(update.join(format!("u{}", i)), format!("upd-{}", i)).await?;
8667 let dst_subdir = dst.join(format!("u{}", i));
8671 tokio::fs::create_dir(&dst_subdir).await?;
8672 for j in 0..3 {
8673 tokio::fs::write(
8674 dst_subdir.join(format!("inner_{}.txt", j)),
8675 format!("old-{}-{}", i, j),
8676 )
8677 .await?;
8678 }
8679 }
8680 let admission = testutils::AdmissionLimit::new().await;
8682 admission.set_files_in_flight(2);
8683 let summary = admission
8684 .run_with_timeout(
8685 std::time::Duration::from_secs(30),
8686 link(
8687 &PROGRESS,
8688 tmp_dir.as_path(),
8689 &src,
8690 &dst,
8691 &Some(update.clone()),
8692 &common_settings(false, true), false,
8694 ),
8695 )
8696 .await
8697 .context("link timed out — pending-meta self-deadlock between site 3 and inner rm")?
8698 .context("link failed")?;
8699 assert_eq!(summary.copy_summary.files_copied, n);
8702 assert_eq!(summary.copy_summary.rm_summary.files_removed, n * 3);
8703 assert_eq!(summary.copy_summary.rm_summary.directories_removed, n);
8704 for i in 0..n {
8706 let content = tokio::fs::read_to_string(dst.join(format!("u{}", i))).await?;
8707 assert_eq!(content, format!("upd-{}", i));
8708 }
8709 Ok(())
8710 }
8711 }
8712
8713 mod race_tests {
8721 use super::*;
8722
8723 fn spawn_file_symlink_swapper(
8727 dir: std::path::PathBuf,
8728 entry_name: &'static str,
8729 sentinel: std::path::PathBuf,
8730 ) -> crate::testutils::SwapperGuard {
8731 crate::testutils::SwapperGuard::spawn(move |stop| {
8732 let entry = dir.join(entry_name);
8733 let staged_real = dir.join("__staged_real");
8734 let staged_link = dir.join("__staged_link");
8735 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
8736 let _ = std::fs::remove_file(&staged_real);
8737 if std::fs::write(&staged_real, b"REAL_CONTENT").is_err() {
8738 continue;
8739 }
8740 let _ = std::fs::rename(&staged_real, &entry);
8741 let _ = std::fs::remove_file(&staged_link);
8742 let _ = std::os::unix::fs::symlink(&sentinel, &staged_link);
8743 let _ = std::fs::rename(&staged_link, &entry);
8744 }
8745 })
8746 }
8747
8748 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
8749 #[traced_test]
8750 async fn hard_link_entry_swap_never_leaks_sentinel() -> Result<(), anyhow::Error> {
8751 let tmp_dir = testutils::create_temp_dir().await?;
8752 let test_path = tmp_dir.as_path();
8753 let sentinel = test_path.join("sentinel_secret");
8756 tokio::fs::write(&sentinel, "SENTINEL_SECRET_CONTENT").await?;
8757 let sentinel_links_before = {
8758 use std::os::unix::fs::MetadataExt;
8759 tokio::fs::symlink_metadata(&sentinel).await?.nlink()
8760 };
8761 let src = test_path.join("src");
8762 let sub = src.join("sub");
8763 tokio::fs::create_dir(&src).await?;
8764 tokio::fs::create_dir(&sub).await?;
8765 tokio::fs::write(sub.join("entry"), "REAL_CONTENT").await?;
8766 let mut swapper = None;
8767 let settings = common_settings(false, true);
8770 let mut failed_iterations = 0usize;
8771 let mut linked_real = 0usize;
8772 let mut linked_symlinks = 0usize;
8773 for i in 0..200 {
8774 if i == 1 {
8776 swapper = Some(spawn_file_symlink_swapper(
8777 sub.clone(),
8778 "entry",
8779 sentinel.clone(),
8780 ));
8781 }
8782 let dst = test_path.join(format!("dst_{i}"));
8783 let result = tokio::time::timeout(
8784 std::time::Duration::from_secs(30),
8785 link(&PROGRESS, test_path, &src, &dst, &None, &settings, false),
8786 )
8787 .await
8788 .expect("link must not hang under concurrent swapping");
8789 let entry_dst = dst.join("sub").join("entry");
8790 let metadata = tokio::fs::symlink_metadata(&entry_dst).await;
8791 if i == 0 {
8792 result
8793 .as_ref()
8794 .expect("the stable regular-file control must succeed");
8795 assert!(
8796 metadata
8797 .as_ref()
8798 .expect("the stable regular-file control must create the entry")
8799 .is_file(),
8800 "the stable regular-file control must create a regular file"
8801 );
8802 }
8803 match result {
8804 Ok(_) => {}
8805 Err(_) => failed_iterations += 1,
8806 }
8807 if let Ok(md) = metadata {
8813 if md.file_type().is_file() {
8814 let content = tokio::fs::read_to_string(&entry_dst).await?;
8815 assert_ne!(
8816 content, "SENTINEL_SECRET_CONTENT",
8817 "iteration {i}: sentinel content leaked into the destination as a regular file"
8818 );
8819 assert_eq!(
8820 content, "REAL_CONTENT",
8821 "iteration {i}: a regular destination file must hold the real content"
8822 );
8823 if i > 0 {
8825 linked_real += 1;
8826 }
8827 } else if md.file_type().is_symlink() {
8828 assert_eq!(
8829 tokio::fs::read_link(&entry_dst).await?,
8830 sentinel,
8831 "iteration {i}: a destination symlink must preserve the literal target"
8832 );
8833 linked_symlinks += 1;
8834 }
8835 }
8836 let _ = tokio::fs::remove_dir_all(&dst).await;
8837 }
8838 drop(swapper);
8839 let sentinel_links_after = {
8842 use std::os::unix::fs::MetadataExt;
8843 tokio::fs::symlink_metadata(&sentinel).await?.nlink()
8844 };
8845 assert_eq!(
8846 sentinel_links_after, sentinel_links_before,
8847 "the sentinel file must never gain a hard link (linkat must not follow the symlink)"
8848 );
8849 tracing::info!(
8852 "link file/symlink swap: failed_iterations={failed_iterations}, linked_real={linked_real}, linked_symlinks={linked_symlinks}"
8853 );
8854 assert!(
8855 linked_real + linked_symlinks > 0,
8856 "expected an actual file or symlink across 199 concurrent iterations"
8857 );
8858 Ok(())
8859 }
8860 }
8861}