1use serde::{Deserialize, Serialize};
26use std::os::unix::fs::MetadataExt;
27use std::os::unix::prelude::PermissionsExt;
28
29mod directory_limits;
30pub use directory_limits::{DirectoryClass, DirectoryLimits};
31
32pub const DEFAULT_OVERWRITE_MANIFEST_MAX_ENTRIES: usize = 5_000_000;
37
38#[derive(Clone, Debug, Deserialize, Serialize)]
50pub enum WireAcls {
51 Unknown,
55 Captured {
58 access: Option<Vec<u8>>,
60 default: Option<Vec<u8>>,
63 },
64}
65
66#[derive(Clone, Debug, Deserialize, Serialize)]
67pub struct Metadata {
68 pub mode: u32,
69 pub uid: u32,
70 pub gid: u32,
71 pub atime: i64,
72 pub mtime: i64,
73 pub atime_nsec: i64,
74 pub mtime_nsec: i64,
75 pub acls: WireAcls,
79}
80
81impl Metadata {
82 #[must_use]
96 pub fn with_acls(mut self, acls: &common::safedir::Acls) -> Self {
97 self.acls = WireAcls::Captured {
98 access: acls.access.clone(),
99 default: acls.default.clone(),
100 };
101 self
102 }
103
104 pub fn captured_acls(&self) -> Option<common::safedir::Acls> {
114 match &self.acls {
115 WireAcls::Unknown => None,
116 WireAcls::Captured { access, default } => Some(common::safedir::Acls {
117 access: access.clone(),
118 default: default.clone(),
119 }),
120 }
121 }
122}
123
124impl common::preserve::Metadata for Metadata {
125 fn uid(&self) -> u32 {
126 self.uid
127 }
128 fn gid(&self) -> u32 {
129 self.gid
130 }
131 fn atime(&self) -> i64 {
132 self.atime
133 }
134 fn atime_nsec(&self) -> i64 {
135 self.atime_nsec
136 }
137 fn mtime(&self) -> i64 {
138 self.mtime
139 }
140 fn mtime_nsec(&self) -> i64 {
141 self.mtime_nsec
142 }
143 fn permissions(&self) -> std::fs::Permissions {
144 std::fs::Permissions::from_mode(self.mode)
145 }
146}
147
148impl common::preserve::Metadata for &Metadata {
149 fn uid(&self) -> u32 {
150 (*self).uid()
151 }
152 fn gid(&self) -> u32 {
153 (*self).gid()
154 }
155 fn atime(&self) -> i64 {
156 (*self).atime()
157 }
158 fn atime_nsec(&self) -> i64 {
159 (*self).atime_nsec()
160 }
161 fn mtime(&self) -> i64 {
162 (*self).mtime()
163 }
164 fn mtime_nsec(&self) -> i64 {
165 (*self).mtime_nsec()
166 }
167 fn permissions(&self) -> std::fs::Permissions {
168 (*self).permissions()
169 }
170}
171
172impl From<&std::fs::Metadata> for Metadata {
173 fn from(metadata: &std::fs::Metadata) -> Self {
179 Metadata {
180 mode: metadata.mode(),
181 uid: metadata.uid(),
182 gid: metadata.gid(),
183 atime: metadata.atime(),
184 mtime: metadata.mtime(),
185 atime_nsec: metadata.atime_nsec(),
186 mtime_nsec: metadata.mtime_nsec(),
187 acls: WireAcls::Unknown,
188 }
189 }
190}
191
192impl From<&common::safedir::FileMeta> for Metadata {
193 fn from(meta: &common::safedir::FileMeta) -> Self {
201 use common::preserve::Metadata as _;
202 Metadata {
203 mode: meta.permissions().mode(),
204 uid: meta.uid(),
205 gid: meta.gid(),
206 atime: meta.atime(),
207 mtime: meta.mtime(),
208 atime_nsec: meta.atime_nsec(),
209 mtime_nsec: meta.mtime_nsec(),
210 acls: WireAcls::Unknown,
211 }
212 }
213}
214
215#[derive(Clone, Debug, Deserialize, Serialize)]
226pub struct ExistingEntry {
227 pub name: std::path::PathBuf,
228 pub is_file: bool,
229 pub metadata: Metadata,
230 pub size: u64,
231}
232
233pub const MANIFEST_CHUNK_BYTE_BUDGET: usize = 4 * 1024 * 1024;
237
238fn estimate_entry_size(entry: &ExistingEntry) -> usize {
242 entry.name.as_os_str().len() + 64
243}
244
245pub fn chunk_manifest(entries: Vec<ExistingEntry>, byte_budget: usize) -> Vec<Vec<ExistingEntry>> {
251 let mut chunks: Vec<Vec<ExistingEntry>> = Vec::new();
252 let mut current: Vec<ExistingEntry> = Vec::new();
253 let mut current_bytes = 0usize;
254 for entry in entries {
255 let size = estimate_entry_size(&entry);
256 if !current.is_empty() && current_bytes + size > byte_budget {
257 chunks.push(std::mem::take(&mut current));
258 current_bytes = 0;
259 }
260 current_bytes += size;
261 current.push(entry);
262 }
263 if !current.is_empty() {
264 chunks.push(current);
265 }
266 chunks
267}
268
269#[derive(Debug, Deserialize, Serialize)]
271pub struct File {
272 pub src: std::path::PathBuf,
273 pub dst: std::path::PathBuf,
274 pub size: u64,
275 pub metadata: Metadata,
276 pub is_root: bool,
277}
278
279#[derive(Debug)]
281pub struct FileMetadata<'a> {
282 pub metadata: &'a Metadata,
283 pub size: u64,
284}
285
286impl<'a> common::preserve::Metadata for FileMetadata<'a> {
287 fn uid(&self) -> u32 {
288 self.metadata.uid()
289 }
290 fn gid(&self) -> u32 {
291 self.metadata.gid()
292 }
293 fn atime(&self) -> i64 {
294 self.metadata.atime()
295 }
296 fn atime_nsec(&self) -> i64 {
297 self.metadata.atime_nsec()
298 }
299 fn mtime(&self) -> i64 {
300 self.metadata.mtime()
301 }
302 fn mtime_nsec(&self) -> i64 {
303 self.metadata.mtime_nsec()
304 }
305 fn permissions(&self) -> std::fs::Permissions {
306 self.metadata.permissions()
307 }
308 fn size(&self) -> u64 {
309 self.size
310 }
311}
312
313#[derive(Debug, Deserialize, Serialize)]
315pub enum SourceMessage {
316 DirectoryBegin {
318 src: std::path::PathBuf,
319 dst: std::path::PathBuf,
320 metadata: Metadata,
321 is_root: bool,
322 keep_if_empty: bool,
324 admission: DirectoryClass,
326 },
327 DirectoryEnd {
329 src: std::path::PathBuf,
330 dst: std::path::PathBuf,
331 entry_count: usize,
332 },
333 Symlink {
335 src: std::path::PathBuf,
336 dst: std::path::PathBuf,
337 target: std::path::PathBuf,
338 metadata: Metadata,
339 is_root: bool,
340 },
341 DiscoveryComplete { has_root_item: bool },
346 FileSkipped {
349 src: std::path::PathBuf,
350 dst: std::path::PathBuf,
351 },
352 FileUnchanged {
357 src: std::path::PathBuf,
358 dst: std::path::PathBuf,
359 },
360}
361
362#[derive(Clone, Debug, Deserialize, Serialize)]
363pub struct SrcDst {
364 pub src: std::path::PathBuf,
365 pub dst: std::path::PathBuf,
366}
367
368#[derive(Clone, Debug, Deserialize, Serialize)]
370pub enum DestinationMessage {
371 DirectoryManifestChunk {
379 dst: std::path::PathBuf,
380 entries: Vec<ExistingEntry>,
381 },
382 DirectoryReady {
384 src: std::path::PathBuf,
385 dst: std::path::PathBuf,
386 },
387 DirectorySkipped {
390 src: std::path::PathBuf,
391 dst: std::path::PathBuf,
392 },
393 DirectoryReleased {
395 src: std::path::PathBuf,
396 dst: std::path::PathBuf,
397 },
398 DestinationDone,
401}
402
403#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
404pub enum RcpdFilesInFlight {
405 Automatic,
406 ResolvedAutomatic(std::num::NonZeroUsize),
407 Explicit(common::ConcurrencyLimit),
408 DeprecatedMaxOpenFiles(common::ConcurrencyLimit),
409}
410
411#[derive(Clone, Debug, Deserialize, Serialize)]
412pub struct RcpdConfig {
413 pub verbose: u8,
414 pub fail_early: bool,
415 pub preview_only: bool,
417 pub max_workers: usize,
418 pub max_blocking_threads: usize,
419 pub files_in_flight: RcpdFilesInFlight,
421 pub ops_throttle: usize,
422 pub iops_throttle: usize,
423 pub chunk_size: usize,
424 pub auto_meta: Option<common::AutoMetaThrottleConfig>,
428 pub auto_meta_histogram: bool,
430 pub auto_meta_histogram_log: Option<String>,
434 pub auto_meta_histogram_interval: std::time::Duration,
436 pub dereference: bool,
438 pub require_toctou_safe: bool,
441 pub overwrite: bool,
442 pub overwrite_compare: String,
443 pub overwrite_manifest_max_entries: usize,
445 pub overwrite_filter: Option<String>,
446 pub ignore_existing: bool,
447 pub skip_specials: bool,
448 pub debug_log_prefix: Option<String>,
449 pub port_ranges: Option<String>,
451 pub progress: bool,
452 pub progress_delay: Option<String>,
453 pub remote_copy_conn_timeout_sec: u64,
454 pub remote_keepalive_sec: u64,
458 pub network_profile: crate::NetworkProfile,
460 pub buffer_size: Option<usize>,
462 pub buffer_retention_limit: Option<usize>,
465 pub max_connections: usize,
468 pub pending_writes_multiplier: usize,
470 pub chrome_trace_prefix: Option<String>,
472 pub timings_prefix: Option<String>,
474 pub timings_detail: bool,
476 pub flamegraph_prefix: Option<String>,
478 pub profile_level: Option<String>,
480 pub tokio_console: bool,
482 pub tokio_console_port: Option<u16>,
484 pub encryption: bool,
486 pub master_cert_fingerprint: Option<CertFingerprint>,
488}
489
490impl RcpdConfig {
491 pub fn to_args(&self) -> Vec<String> {
492 let mut args = vec![
493 format!("--max-workers={}", self.max_workers),
494 format!("--max-blocking-threads={}", self.max_blocking_threads),
495 format!("--ops-throttle={}", self.ops_throttle),
496 format!("--iops-throttle={}", self.iops_throttle),
497 format!("--chunk-size={}", self.chunk_size),
498 format!("--overwrite-compare={}", self.overwrite_compare),
499 format!(
500 "--overwrite-manifest-max-entries={}",
501 self.overwrite_manifest_max_entries
502 ),
503 ];
504 if self.verbose > 0 {
505 args.push(format!("-{}", "v".repeat(self.verbose as usize)));
506 }
507 if self.fail_early {
508 args.push("--fail-early".to_string());
509 }
510 if self.preview_only {
511 args.push("--preview-only".to_string());
512 }
513 match self.files_in_flight {
514 RcpdFilesInFlight::Automatic => {}
515 RcpdFilesInFlight::ResolvedAutomatic(value) => {
516 args.push(format!("--resolved-automatic-files-in-flight={value}"));
517 }
518 RcpdFilesInFlight::Explicit(value) => {
519 args.push(format!("--max-files-in-flight={value}"));
520 }
521 RcpdFilesInFlight::DeprecatedMaxOpenFiles(value) => {
522 let value = match value {
523 common::ConcurrencyLimit::Unlimited => 0,
524 common::ConcurrencyLimit::Limited(value) => value.get(),
525 };
526 args.push(format!("--forwarded-legacy-files-in-flight={value}"));
527 }
528 }
529 if self.dereference {
530 args.push("--dereference".to_string());
531 }
532 if self.require_toctou_safe {
533 args.push("--require-toctou-safe".to_string());
534 }
535 if self.overwrite {
536 args.push("--overwrite".to_string());
537 if let Some(ref filter) = self.overwrite_filter {
538 args.push(format!("--overwrite-filter={filter}"));
539 }
540 }
541 if self.ignore_existing {
542 args.push("--ignore-existing".to_string());
543 }
544 if self.skip_specials {
545 args.push("--skip-specials".to_string());
546 }
547 if let Some(ref prefix) = self.debug_log_prefix {
548 args.push(format!("--debug-log-prefix={prefix}"));
549 }
550 if let Some(ref ranges) = self.port_ranges {
551 args.push(format!("--port-ranges={ranges}"));
552 }
553 if self.progress {
554 args.push("--progress".to_string());
555 }
556 if let Some(ref delay) = self.progress_delay {
557 args.push(format!("--progress-delay={delay}"));
558 }
559 args.push(format!(
560 "--remote-copy-conn-timeout-sec={}",
561 self.remote_copy_conn_timeout_sec
562 ));
563 args.push(format!(
564 "--remote-keepalive-sec={}",
565 self.remote_keepalive_sec
566 ));
567 args.push(format!("--network-profile={}", self.network_profile));
569 if let Some(v) = self.buffer_size {
571 args.push(format!("--buffer-size={v}"));
572 }
573 if let Some(v) = self.buffer_retention_limit {
574 args.push(format!("--buffer-retention-limit={v}"));
575 }
576 args.push(format!("--max-connections={}", self.max_connections));
577 args.push(format!(
578 "--pending-writes-multiplier={}",
579 self.pending_writes_multiplier
580 ));
581 let profiling_enabled =
583 self.chrome_trace_prefix.is_some() || self.flamegraph_prefix.is_some();
584 if let Some(ref prefix) = self.chrome_trace_prefix {
585 args.push(format!("--chrome-trace={prefix}"));
586 }
587 if let Some(ref prefix) = self.timings_prefix {
588 args.push(format!("--timings={prefix}"));
589 }
590 if self.timings_detail {
591 args.push("--timings-detail".to_string());
592 }
593 if let Some(ref prefix) = self.flamegraph_prefix {
594 args.push(format!("--flamegraph={prefix}"));
595 }
596 if profiling_enabled && let Some(level) = &self.profile_level {
597 args.push(format!("--profile-level={level}"));
598 }
599 if self.tokio_console {
600 args.push("--tokio-console".to_string());
601 }
602 if let Some(port) = self.tokio_console_port {
603 args.push(format!("--tokio-console-port={port}"));
604 }
605 if !self.encryption {
606 args.push("--no-encryption".to_string());
607 }
608 if let Some(fp) = self.master_cert_fingerprint {
609 args.push(format!(
610 "--master-cert-fp={}",
611 crate::tls::fingerprint_to_hex(&fp)
612 ));
613 }
614 if let Some(auto) = &self.auto_meta {
617 args.push("--auto-meta-throttle".to_string());
618 args.push(format!("--auto-meta-initial-cwnd={}", auto.initial_cwnd));
619 args.push(format!("--auto-meta-min-cwnd={}", auto.min_cwnd));
620 args.push(format!("--auto-meta-max-cwnd={}", auto.max_cwnd));
621 args.push(format!("--auto-meta-alpha={}", auto.alpha));
622 args.push(format!("--auto-meta-beta={}", auto.beta));
623 args.push(format!(
624 "--auto-meta-baseline-percentile={}",
625 auto.baseline_percentile,
626 ));
627 args.push(format!(
628 "--auto-meta-current-percentile={}",
629 auto.current_percentile,
630 ));
631 args.push(format!("--auto-meta-increase-step={}", auto.increase_step));
632 args.push(format!("--auto-meta-decrease-step={}", auto.decrease_step));
633 args.push(format!(
634 "--auto-meta-long-window={}",
635 humantime::format_duration(auto.long_window),
636 ));
637 args.push(format!(
638 "--auto-meta-short-window={}",
639 humantime::format_duration(auto.short_window),
640 ));
641 args.push(format!(
642 "--auto-meta-tick-interval={}",
643 humantime::format_duration(auto.tick_interval),
644 ));
645 }
646 if let Some(path) = &self.auto_meta_histogram_log {
654 args.push(format!("--auto-meta-histogram-log={path}"));
655 args.push(format!(
656 "--auto-meta-histogram-interval={}",
657 humantime::format_duration(self.auto_meta_histogram_interval),
658 ));
659 }
660 args
661 }
662}
663
664#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
665pub enum RcpdRole {
666 Source,
667 Destination,
668}
669
670impl std::fmt::Display for RcpdRole {
671 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
672 match self {
673 RcpdRole::Source => write!(f, "source"),
674 RcpdRole::Destination => write!(f, "destination"),
675 }
676 }
677}
678
679impl std::str::FromStr for RcpdRole {
680 type Err = anyhow::Error;
681 fn from_str(s: &str) -> Result<Self, Self::Err> {
682 match s.to_lowercase().as_str() {
683 "source" => Ok(RcpdRole::Source),
684 "destination" | "dest" => Ok(RcpdRole::Destination),
685 _ => Err(anyhow::anyhow!("invalid role: {}", s)),
686 }
687 }
688}
689
690#[derive(Clone, Debug, Deserialize, Serialize)]
691pub struct TracingHello {
692 pub role: RcpdRole,
693 pub is_tracing: bool,
695}
696
697pub type CertFingerprint = [u8; 32];
699
700#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
721pub struct ExtendedMetadataCapture {
722 pub file_acl: bool,
724 pub dir_acl: bool,
726 pub root_acl_notice: bool,
734}
735
736impl ExtendedMetadataCapture {
737 pub fn for_preserve(preserve: &common::preserve::Settings) -> Self {
746 Self {
747 file_acl: preserve.file.acl,
748 dir_acl: preserve.dir.acl,
749 root_acl_notice: preserve.requests_preservation(),
750 }
751 }
752}
753
754impl From<ExtendedMetadataCapture> for common::safedir::RootAclNotice {
755 fn from(capture: ExtendedMetadataCapture) -> Self {
761 Self {
762 wanted: capture.root_acl_notice,
763 file_acl_preserved: capture.file_acl,
764 dir_acl_preserved: capture.dir_acl,
765 }
766 }
767}
768
769#[derive(Clone, Debug, Deserialize, Serialize)]
770pub enum MasterHello {
771 Source {
772 src: std::path::PathBuf,
773 dst: std::path::PathBuf,
774 dest_cert_fingerprint: Option<CertFingerprint>,
776 filter: Option<common::filter::FilterSettings>,
778 dry_run: Option<common::config::DryRunMode>,
780 capture: ExtendedMetadataCapture,
783 },
784 Destination {
785 source_control_addr: std::net::SocketAddr,
787 source_data_addr: std::net::SocketAddr,
789 server_name: String,
790 preserve: common::preserve::Settings,
791 source_cert_fingerprint: Option<CertFingerprint>,
793 dry_run: bool,
795 },
796}
797
798#[derive(Clone, Debug, Deserialize, Serialize)]
799pub struct SourceMasterHello {
800 pub control_addr: std::net::SocketAddr,
802 pub data_addr: std::net::SocketAddr,
804 pub server_name: String,
805}
806
807pub use common::RuntimeStats;
809
810#[derive(Clone, Debug, Deserialize, Serialize)]
811pub enum RcpdResult {
812 Success {
813 message: String,
814 summary: common::copy::Summary,
815 runtime_stats: common::RuntimeStats,
816 },
817 Failure {
818 error: String,
819 summary: common::copy::Summary,
820 runtime_stats: common::RuntimeStats,
821 },
822}
823
824#[cfg(test)]
825mod tests {
826 use super::*;
827
828 fn mk_entry(name: &str) -> ExistingEntry {
829 ExistingEntry {
830 name: std::path::PathBuf::from(name),
831 is_file: true,
832 metadata: Metadata {
833 mode: 0o644,
834 uid: 0,
835 gid: 0,
836 atime: 0,
837 mtime: 0,
838 atime_nsec: 0,
839 mtime_nsec: 0,
840 acls: WireAcls::Unknown,
841 },
842 size: 0,
843 }
844 }
845
846 #[test]
847 fn chunk_manifest_empty_yields_no_chunks() {
848 assert!(chunk_manifest(vec![], MANIFEST_CHUNK_BYTE_BUDGET).is_empty());
849 }
850
851 #[test]
852 fn chunk_manifest_small_is_single_chunk() {
853 let entries: Vec<_> = (0..100).map(|i| mk_entry(&format!("f{i}.txt"))).collect();
854 let chunks = chunk_manifest(entries, MANIFEST_CHUNK_BYTE_BUDGET);
855 assert_eq!(chunks.len(), 1);
856 assert_eq!(chunks[0].len(), 100);
857 }
858
859 #[test]
860 fn chunk_manifest_splits_and_preserves_all_entries_in_order() {
861 let entries: Vec<_> = (0..1000)
862 .map(|i| mk_entry(&format!("file_{i:04}.dat")))
863 .collect();
864 let chunks = chunk_manifest(entries.clone(), 256);
866 assert!(
867 chunks.len() > 1,
868 "tiny budget should produce multiple chunks"
869 );
870 for chunk in &chunks {
873 if chunk.len() > 1 {
874 let total: usize = chunk.iter().map(estimate_entry_size).sum();
875 assert!(total <= 256, "multi-entry chunk exceeds budget: {total}");
876 }
877 }
878 let flat: Vec<_> = chunks.into_iter().flatten().collect();
880 assert_eq!(flat.len(), entries.len());
881 for (got, want) in flat.iter().zip(entries.iter()) {
882 assert_eq!(got.name, want.name);
883 }
884 }
885
886 #[test]
887 fn chunk_manifest_entry_larger_than_budget_gets_its_own_chunk() {
888 let chunks = chunk_manifest(vec![mk_entry("a"), mk_entry("b")], 1);
890 assert_eq!(chunks.len(), 2);
891 assert_eq!(chunks[0].len(), 1);
892 assert_eq!(chunks[1].len(), 1);
893 }
894
895 #[test]
896 fn chunk_manifest_splits_a_large_manifest_at_the_production_budget() {
897 let per_entry = estimate_entry_size(&mk_entry("file_0000000.dat"));
902 let n = (MANIFEST_CHUNK_BYTE_BUDGET / per_entry) * 2 + 1000;
903 let entries: Vec<_> = (0..n)
904 .map(|i| mk_entry(&format!("file_{i:07}.dat")))
905 .collect();
906 let chunks = chunk_manifest(entries.clone(), MANIFEST_CHUNK_BYTE_BUDGET);
907 assert!(
908 chunks.len() > 1,
909 "a manifest larger than the 4 MiB budget must span multiple chunks, got {}",
910 chunks.len()
911 );
912 for chunk in &chunks {
914 if chunk.len() > 1 {
915 let total: usize = chunk.iter().map(estimate_entry_size).sum();
916 assert!(
917 total <= MANIFEST_CHUNK_BYTE_BUDGET,
918 "a chunk exceeds the production budget: {total}"
919 );
920 }
921 }
922 let flat: Vec<_> = chunks.into_iter().flatten().collect();
924 assert_eq!(
925 flat.len(),
926 entries.len(),
927 "reassembly must preserve every entry"
928 );
929 assert!(
930 flat.iter().zip(&entries).all(|(a, b)| a.name == b.name),
931 "reassembly must preserve order"
932 );
933 }
934
935 #[test]
936 fn metadata_carries_acl_bytes_verbatim_through_a_wire_round_trip() {
937 let access: Vec<u8> = (0u8..=200).collect();
941 let default: Vec<u8> = (0u8..=100).rev().collect();
942 let meta = mk_entry("f").metadata.with_acls(&common::safedir::Acls {
943 access: Some(access.clone()),
944 default: Some(default.clone()),
945 });
946 let bytes = bitcode::serialize(&meta).unwrap();
948 let back: Metadata = bitcode::deserialize(&bytes).unwrap();
949 assert_eq!(
951 back.captured_acls(),
952 Some(common::safedir::Acls {
953 access: Some(access),
954 default: Some(default),
955 })
956 );
957 }
958
959 #[test]
960 fn metadata_built_from_a_stat_snapshot_carries_unknown_acls() {
961 let meta = Metadata::from(&std::fs::metadata(".").unwrap());
966 assert_eq!(meta.captured_acls(), None);
967 }
968
969 #[test]
970 fn with_acls_round_trips_the_absent_case_as_a_clear_request() {
971 let meta = mk_entry("f")
974 .metadata
975 .with_acls(&common::safedir::Acls::default());
976 assert_eq!(meta.captured_acls(), Some(common::safedir::Acls::default()));
977 }
978
979 #[test]
980 fn capture_mirrors_the_preserve_settings_it_is_derived_from() {
981 assert_eq!(
986 ExtendedMetadataCapture::for_preserve(&common::preserve::preserve_all_with_acls()),
987 ExtendedMetadataCapture {
988 file_acl: true,
989 dir_acl: true,
990 root_acl_notice: true,
993 }
994 );
995 assert_eq!(
996 ExtendedMetadataCapture::for_preserve(&common::preserve::preserve_all()),
997 ExtendedMetadataCapture {
998 file_acl: false,
999 dir_acl: false,
1000 root_acl_notice: true,
1001 },
1002 "`all` deliberately excludes ACLs, so it must not make the source pay the per-entry \
1003 read — but it DID ask for metadata fidelity, so the one root probe behind the notice \
1004 is exactly the case the notice exists for"
1005 );
1006 let mut file_only = common::preserve::preserve_none();
1007 file_only.file.acl = true;
1008 assert_eq!(
1009 ExtendedMetadataCapture::for_preserve(&file_only),
1010 ExtendedMetadataCapture {
1011 file_acl: true,
1012 dir_acl: false,
1013 root_acl_notice: true,
1014 }
1015 );
1016 }
1017
1018 #[test]
1019 fn a_copy_asking_for_no_preservation_makes_the_source_read_nothing() {
1020 assert_eq!(
1023 ExtendedMetadataCapture::for_preserve(&common::preserve::preserve_none()),
1024 ExtendedMetadataCapture::default(),
1025 );
1026 }
1027
1028 #[test]
1029 fn the_notice_the_source_reassembles_matches_the_capture_it_came_from() {
1030 let capture = ExtendedMetadataCapture {
1033 file_acl: true,
1034 dir_acl: false,
1035 root_acl_notice: true,
1036 };
1037 assert_eq!(
1038 common::safedir::RootAclNotice::from(capture),
1039 common::safedir::RootAclNotice {
1040 wanted: true,
1041 file_acl_preserved: true,
1042 dir_acl_preserved: false,
1043 }
1044 );
1045 }
1046
1047 fn minimal_rcpd_config() -> RcpdConfig {
1048 RcpdConfig {
1049 verbose: 0,
1050 fail_early: false,
1051 preview_only: false,
1052 max_workers: 0,
1053 max_blocking_threads: 0,
1054 files_in_flight: RcpdFilesInFlight::Explicit(common::ConcurrencyLimit::Limited(
1055 std::num::NonZeroUsize::new(4).unwrap(),
1056 )),
1057 ops_throttle: 0,
1058 iops_throttle: 0,
1059 chunk_size: 0,
1060 auto_meta: None,
1061 auto_meta_histogram: false,
1062 auto_meta_histogram_log: None,
1063 auto_meta_histogram_interval: std::time::Duration::from_secs(1),
1064 dereference: false,
1065 require_toctou_safe: false,
1066 overwrite: false,
1067 overwrite_compare: "size,mtime".to_string(),
1068 overwrite_filter: None,
1069 ignore_existing: false,
1070 skip_specials: false,
1071 debug_log_prefix: None,
1072 port_ranges: None,
1073 progress: false,
1074 progress_delay: None,
1075 remote_copy_conn_timeout_sec: 30,
1076 remote_keepalive_sec: crate::DEFAULT_REMOTE_KEEPALIVE_SEC,
1077 network_profile: crate::NetworkProfile::default(),
1078 buffer_size: None,
1079 buffer_retention_limit: None,
1080 max_connections: 1,
1081 pending_writes_multiplier: 1,
1082 chrome_trace_prefix: None,
1083 timings_prefix: None,
1084 timings_detail: false,
1085 flamegraph_prefix: None,
1086 profile_level: None,
1087 tokio_console: false,
1088 tokio_console_port: None,
1089 encryption: true,
1090 master_cert_fingerprint: None,
1091 overwrite_manifest_max_entries: DEFAULT_OVERWRITE_MANIFEST_MAX_ENTRIES,
1092 }
1093 }
1094
1095 #[test]
1096 fn to_args_propagates_preview_startup_policy() {
1097 let mut config = minimal_rcpd_config();
1098 assert!(!config.to_args().iter().any(|arg| arg == "--preview-only"));
1099 config.preview_only = true;
1100 assert!(config.to_args().iter().any(|arg| arg == "--preview-only"));
1101 }
1102
1103 #[test]
1104 fn to_args_propagates_scoped_timing_options() {
1105 let mut config = minimal_rcpd_config();
1106 config.timings_prefix = Some("/tmp/profile with spaces".to_string());
1107 config.timings_detail = true;
1108 let args = config.to_args();
1109 assert!(
1110 args.iter()
1111 .any(|arg| arg == "--timings=/tmp/profile with spaces")
1112 );
1113 assert!(args.iter().any(|arg| arg == "--timings-detail"));
1114 assert!(!args.iter().any(|arg| arg.starts_with("--profile-level=")));
1115 }
1116
1117 #[test]
1118 fn to_args_includes_overwrite_manifest_max_entries() {
1119 let mut config = minimal_rcpd_config();
1120 config.overwrite_manifest_max_entries = 123_456;
1121 let args = config.to_args();
1122 assert!(
1123 args.iter()
1124 .any(|a| a == "--overwrite-manifest-max-entries=123456"),
1125 "expected manifest cap flag in {args:?}"
1126 );
1127 }
1128
1129 #[test]
1130 fn to_args_propagates_finite_files_in_flight() {
1131 let mut config = minimal_rcpd_config();
1132 config.files_in_flight = RcpdFilesInFlight::Explicit(common::ConcurrencyLimit::Limited(
1133 std::num::NonZeroUsize::new(7).unwrap(),
1134 ));
1135 let args = config.to_args();
1136 assert!(args.iter().any(|arg| arg == "--max-files-in-flight=7"));
1137 }
1138
1139 #[test]
1140 fn to_args_propagates_explicit_unlimited_files_in_flight() {
1141 let mut config = minimal_rcpd_config();
1142 config.files_in_flight = RcpdFilesInFlight::Explicit(common::ConcurrencyLimit::Unlimited);
1143 let args = config.to_args();
1144 assert!(
1145 args.iter()
1146 .any(|arg| arg == "--max-files-in-flight=unlimited")
1147 );
1148 assert!(
1149 !args
1150 .iter()
1151 .any(|arg| arg.starts_with("--forwarded-legacy-files-in-flight"))
1152 );
1153 }
1154
1155 #[test]
1156 fn to_args_preserves_legacy_finite_files_in_flight() {
1157 let mut config = minimal_rcpd_config();
1158 config.files_in_flight = RcpdFilesInFlight::DeprecatedMaxOpenFiles(
1159 common::ConcurrencyLimit::Limited(std::num::NonZeroUsize::new(7).unwrap()),
1160 );
1161 let args = config.to_args();
1162 assert!(
1163 args.iter()
1164 .any(|arg| arg == "--forwarded-legacy-files-in-flight=7")
1165 );
1166 assert!(!args.iter().any(|arg| arg.starts_with("--max-open-files")));
1167 }
1168
1169 #[test]
1170 fn to_args_preserves_legacy_unlimited_files_in_flight() {
1171 let mut config = minimal_rcpd_config();
1172 config.files_in_flight =
1173 RcpdFilesInFlight::DeprecatedMaxOpenFiles(common::ConcurrencyLimit::Unlimited);
1174 let args = config.to_args();
1175 assert!(
1176 args.iter()
1177 .any(|arg| arg == "--forwarded-legacy-files-in-flight=0")
1178 );
1179 assert!(!args.iter().any(|arg| arg.starts_with("--max-open-files")));
1180 }
1181
1182 #[test]
1183 fn to_args_propagates_effective_connection_count() {
1184 let mut config = minimal_rcpd_config();
1185 config.max_connections = 7;
1186 assert!(
1187 config
1188 .to_args()
1189 .iter()
1190 .any(|arg| arg == "--max-connections=7")
1191 );
1192 }
1193
1194 #[test]
1195 fn rcpd_config_omits_an_automatic_file_limit_override() {
1196 let mut config = minimal_rcpd_config();
1197 config.files_in_flight = RcpdFilesInFlight::Automatic;
1198 let args = config.to_args();
1199 assert!(!args.iter().any(|arg| arg.contains("files-in-flight")));
1200 assert!(!args.iter().any(|arg| arg.starts_with("--max-open-files")));
1201 }
1202
1203 #[test]
1204 fn rcpd_config_marks_a_resolved_automatic_file_limit() {
1205 let mut config = minimal_rcpd_config();
1206 config.files_in_flight =
1207 RcpdFilesInFlight::ResolvedAutomatic(std::num::NonZeroUsize::new(7).unwrap());
1208 let args = config.to_args();
1209 assert!(
1210 args.iter()
1211 .any(|arg| arg == "--resolved-automatic-files-in-flight=7")
1212 );
1213 assert!(
1214 !args
1215 .iter()
1216 .any(|arg| arg.starts_with("--max-files-in-flight"))
1217 );
1218 }
1219
1220 #[test]
1221 fn rcpd_config_uses_the_public_argument_for_an_explicit_finite_limit() {
1222 let mut config = minimal_rcpd_config();
1223 config.files_in_flight = RcpdFilesInFlight::Explicit(common::ConcurrencyLimit::Limited(
1224 std::num::NonZeroUsize::new(7).unwrap(),
1225 ));
1226 let args = config.to_args();
1227 assert!(args.iter().any(|arg| arg == "--max-files-in-flight=7"));
1228 }
1229
1230 #[test]
1231 fn to_args_mirrors_require_toctou_safe() {
1232 let mut config = minimal_rcpd_config();
1233 config.require_toctou_safe = true;
1234 let args = config.to_args();
1235 assert!(
1236 args.iter().any(|a| a == "--require-toctou-safe"),
1237 "expected --require-toctou-safe in {args:?}"
1238 );
1239 let config = minimal_rcpd_config();
1240 assert!(
1241 !config
1242 .to_args()
1243 .iter()
1244 .any(|a| a == "--require-toctou-safe"),
1245 "flag must be omitted when off"
1246 );
1247 }
1248
1249 #[test]
1252 fn to_args_propagates_remote_keepalive_sec() {
1253 let mut config = minimal_rcpd_config();
1254 config.remote_keepalive_sec = 45;
1255 assert!(
1256 config
1257 .to_args()
1258 .iter()
1259 .any(|a| a == "--remote-keepalive-sec=45"),
1260 "expected the keepalive budget in {:?}",
1261 config.to_args()
1262 );
1263 config.remote_keepalive_sec = 0;
1265 assert!(
1266 config
1267 .to_args()
1268 .iter()
1269 .any(|a| a == "--remote-keepalive-sec=0"),
1270 "expected the disabling value to be passed through, not dropped"
1271 );
1272 let default_args = minimal_rcpd_config().to_args();
1273 assert!(
1274 default_args.iter().any(|a| a
1275 == &format!(
1276 "--remote-keepalive-sec={}",
1277 crate::DEFAULT_REMOTE_KEEPALIVE_SEC
1278 )),
1279 "the default must be passed explicitly so rcpd cannot drift from the master: {default_args:?}"
1280 );
1281 }
1282
1283 #[test]
1284 fn to_args_omits_auto_meta_throttle_when_none() {
1285 let args = minimal_rcpd_config().to_args();
1286 let throttle_flags = [
1288 "--auto-meta-throttle",
1289 "--auto-meta-initial-cwnd",
1290 "--auto-meta-min-cwnd",
1291 "--auto-meta-max-cwnd",
1292 "--auto-meta-alpha",
1293 "--auto-meta-beta",
1294 "--auto-meta-baseline-percentile",
1295 "--auto-meta-current-percentile",
1296 "--auto-meta-increase-step",
1297 "--auto-meta-decrease-step",
1298 "--auto-meta-long-window",
1299 "--auto-meta-short-window",
1300 "--auto-meta-tick-interval",
1301 ];
1302 for flag in throttle_flags {
1303 assert!(
1304 !args.iter().any(|a| a.starts_with(flag)),
1305 "throttle flag {flag} should not be emitted when auto_meta is None: {args:?}",
1306 );
1307 }
1308 for arg in &args {
1310 assert!(
1311 !arg.starts_with("--auto-meta-histogram"),
1312 "must not emit any histogram flag when histograms are off, found: {arg}",
1313 );
1314 }
1315 }
1316
1317 #[test]
1318 fn to_args_propagates_all_auto_meta_fields() {
1319 let mut config = minimal_rcpd_config();
1320 config.auto_meta = Some(common::AutoMetaThrottleConfig {
1321 initial_cwnd: 8,
1322 min_cwnd: 2,
1323 max_cwnd: 128,
1324 alpha: 1.2,
1325 beta: 1.6,
1326 increase_step: 2,
1327 decrease_step: 3,
1328 baseline_percentile: 0.4,
1329 current_percentile: 0.6,
1330 long_window: std::time::Duration::from_secs(20),
1331 short_window: std::time::Duration::from_secs(2),
1332 tick_interval: std::time::Duration::from_millis(75),
1333 });
1334 let args = config.to_args();
1335 let has = |needle: &str| args.iter().any(|a| a == needle);
1336 let has_prefix = |needle: &str| args.iter().any(|a| a.starts_with(needle));
1337 assert!(has("--auto-meta-throttle"));
1338 assert!(has("--auto-meta-initial-cwnd=8"));
1339 assert!(has("--auto-meta-min-cwnd=2"));
1340 assert!(has("--auto-meta-max-cwnd=128"));
1341 assert!(has_prefix("--auto-meta-alpha=1.2"));
1342 assert!(has_prefix("--auto-meta-beta=1.6"));
1343 assert!(has_prefix("--auto-meta-baseline-percentile=0.4"));
1344 assert!(has_prefix("--auto-meta-current-percentile=0.6"));
1345 assert!(has("--auto-meta-increase-step=2"));
1346 assert!(has("--auto-meta-decrease-step=3"));
1347 assert!(has_prefix("--auto-meta-long-window="));
1348 assert!(has_prefix("--auto-meta-short-window="));
1349 assert!(has_prefix("--auto-meta-tick-interval="));
1350 }
1351
1352 #[test]
1353 fn to_args_omits_histogram_flags_when_disabled() {
1354 let mut config = minimal_rcpd_config();
1358 config.auto_meta_histogram = false;
1359 config.auto_meta_histogram_log = None;
1360 let args = config.to_args();
1361 for arg in &args {
1362 assert!(
1363 !arg.starts_with("--auto-meta-histogram"),
1364 "must not emit histogram flag when disabled, found: {arg}",
1365 );
1366 }
1367 }
1368
1369 #[test]
1370 fn to_args_omits_panel_only_flag_when_no_log_path() {
1371 let mut config = minimal_rcpd_config();
1375 config.auto_meta_histogram = true;
1376 config.auto_meta_histogram_log = None;
1377 let args = config.to_args();
1378 for arg in &args {
1379 assert!(
1380 !arg.starts_with("--auto-meta-histogram"),
1381 "panel-only flag must not be forwarded to rcpd, found: {arg}",
1382 );
1383 }
1384 }
1385
1386 #[test]
1387 fn to_args_forwards_histogram_log_and_interval_when_log_path_set() {
1388 let mut config = minimal_rcpd_config();
1389 config.auto_meta_histogram = false; config.auto_meta_histogram_log = Some("/tmp/foo.hdr".into());
1391 config.auto_meta_histogram_interval = std::time::Duration::from_millis(500);
1392 let args = config.to_args();
1393 assert!(
1394 args.iter()
1395 .any(|a| a == "--auto-meta-histogram-log=/tmp/foo.hdr")
1396 );
1397 assert!(
1398 args.iter()
1399 .any(|a| a.starts_with("--auto-meta-histogram-interval="))
1400 );
1401 assert!(
1404 !args.iter().any(|a| a == "--auto-meta-histogram"),
1405 "panel-only flag must not be forwarded; the log flag implies the pipeline",
1406 );
1407 }
1408}