Skip to main content

remote/protocol/
mod.rs

1//! Remote copy protocol definitions for source-destination communication.
2//!
3//! The source listens on a bidirectional control port and a pooled file-data port. Each source
4//! directory sends [`SourceMessage::DirectoryBegin`] before its children and
5//! [`SourceMessage::DirectoryEnd`] with its admitted direct-child count after enumeration. The
6//! destination responds with manifest chunks followed by [`DestinationMessage::DirectoryReady`],
7//! or rejects the directory with [`DestinationMessage::DirectorySkipped`]. File jobs wait for
8//! readiness while directory discovery proceeds independently.
9//!
10//! Directory finalization requires Ready to be flushed, End to be received, and every admitted
11//! child to be terminal. A child directory completes its parent entry after its own finalization
12//! or once upon rejection. [`SourceMessage::DiscoveryComplete`] closes structural discovery;
13//! file data and file outcomes can still arrive afterward.
14//!
15//! Sources report counted pre-header failures with [`SourceMessage::FileSkipped`] and retain
16//! their original errors. Destinations retain their own filesystem errors and use directory
17//! rejection to stop source subtree work. Fatal failures cancel the session and admission waits.
18//!
19//! [`DestinationMessage::DestinationDone`] signals completion. The source drains owned file
20//! results before closing its pool and control sender; fatal teardown cancels the pool before
21//! joining blocked work. Data and control EOF are unordered transport effects.
22//!
23//! See `docs/remote_protocol.md` for ordering, validation, security, and lifecycle guarantees.
24
25use 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
32/// Default cap on the number of pre-existing destination entries the destination will put in a
33/// directory's overwrite/ignore-existing manifest. Above this, the manifest is omitted and that
34/// directory falls back to transferring-and-draining files (see `docs/remote_protocol.md`). High
35/// by default — rcp typically runs on large hosts; the cap is a backstop, not a normal limit.
36pub const DEFAULT_OVERWRITE_MANIFEST_MAX_ENTRIES: usize = 5_000_000;
37
38/// A source entry's ACL payload as captured for the wire — or the fact that it was never captured.
39///
40/// The distinction between the two non-carrying states is load-bearing (`docs/remote_protocol.md`
41/// §2.5). `Captured` with `None` fields is an AUTHORITATIVE "the source has no such ACL", which
42/// the destination reproduces by REMOVING the attribute — not by leaving whatever it inherited
43/// (see [`common::safedir::apply_acls_fd`]). `Unknown` says the wire carries no ACL information at
44/// all: either the master never asked ([`ExtendedMetadataCapture`]), or the source COULD NOT read
45/// them (a committed directory that failed to open, whose copy is already recorded as an error) —
46/// and the destination must leave the destination entry's ACLs alone. Treating unavailable ACLs as
47/// an authoritative clear would strip a reused destination directory's access and default ACLs
48/// during a source read failure.
49#[derive(Clone, Debug, Deserialize, Serialize)]
50pub enum WireAcls {
51    /// No ACL information: not captured, or unreadable at the source. The destination must not
52    /// touch the destination entry's ACLs (for a strict-mode locked reused directory, its
53    /// original default ACL is restored by the lockdown guard).
54    Unknown,
55    /// Read from the source entry's held descriptor:
56    /// authoritative, including the "has none" case.
57    Captured {
58        /// `system.posix_acl_access`; `None` = the source has none (an instruction to REMOVE).
59        access: Option<Vec<u8>>,
60        /// `system.posix_acl_default`; directories only (files have no default ACL), same `None`
61        /// semantics.
62        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    /// The source's POSIX ACLs — or [`WireAcls::Unknown`] when they were never read (capture off,
76    /// or the source could not read them). Only ever `Captured` when the master asked via
77    /// [`ExtendedMetadataCapture`].
78    pub acls: WireAcls,
79}
80
81impl Metadata {
82    /// Attach a source entry's POSIX ACLs, carrying the kernel's bytes VERBATIM.
83    ///
84    /// The bytes are never rebuilt or reordered. POSIX.1e requires canonical entry order
85    /// (`USER_OBJ`, named users by ascending uid, `GROUP_OBJ`, named groups by ascending gid,
86    /// `MASK`, `OTHER`) and the kernel rejects anything else with `EINVAL` — passing through what
87    /// the source kernel already validated sidesteps that entirely. The format is defined
88    /// little-endian (`__le16`/`__le32`), so it is portable across hosts as-is. Any future code
89    /// that CONSTRUCTS an ACL (id remapping, a synthesized entry) must sort canonically itself.
90    ///
91    /// This is a builder rather than a field the [`From`] impls fill because neither of them has an
92    /// fd to read from: every site that SHOULD carry ACLs is therefore a visible call, and a site
93    /// that does not stays [`WireAcls::Unknown`] — which the destination reads as "leave the
94    /// destination's ACLs alone", never as a clear.
95    #[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    /// The ACLs this wire metadata carries, in the shape the destination applier takes — or
105    /// `None` when they are [`WireAcls::Unknown`] and the destination must not touch the
106    /// destination entry's ACLs.
107    ///
108    /// A `Some` holding all-`None` fields means "the source had no ACL", which is a request to
109    /// CLEAR, not to leave the destination alone. That is safe to hand the applier because the
110    /// source only reads ACLs when the master asked it to, and the master derives that request
111    /// from the very same `preserve` settings it hands the destination — see
112    /// [`ExtendedMetadataCapture::for_preserve`].
113    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    /// ACLs stay [`WireAcls::Unknown`]: a `stat` snapshot carries no fd, and reading an ACL by
174    /// path would answer from whatever inode the name resolves to now rather than the one this
175    /// snapshot describes. Call sites that should carry ACLs add them with
176    /// [`Metadata::with_acls`]; a site that cannot (the source failed to read them) correctly
177    /// leaves them `Unknown`, which the destination reads as "do not touch", never as a clear.
178    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    /// Build a wire `Metadata` from an fd-pinned [`common::safedir::FileMeta`]
194    /// snapshot (obtained via `fstat`/`fstatat` during a TOCTOU-safe walk),
195    /// reading every field through the shared `preserve::Metadata` trait so it
196    /// stays in lock-step with the `&std::fs::Metadata` conversion above.
197    ///
198    /// ACLs stay [`WireAcls::Unknown`] here too: a `FileMeta` is a detached snapshot, not the fd
199    /// it came from, so it cannot answer an ACL probe. See [`Metadata::with_acls`].
200    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/// One pre-existing destination directory entry, sent in a `DirectoryManifestChunk` so the
216/// source can skip transferring identical files. `name` is the child name (serialized as a
217/// `PathBuf`, matching the rest of the protocol's path handling). `metadata`/`size` are only
218/// meaningful when `is_file`.
219///
220/// The `metadata`'s ACL fields are always `None` here and deliberately so: the manifest exists to
221/// answer `--overwrite-compare` (default `size,mtime`), which has no `acl` term, so an ACL-only
222/// difference does not make a file "changed" and a skipped file keeps its old ACL. That is the same
223/// shape as `mode`, which the default comparison also ignores; closing it means an `acl` term in
224/// the compare DSL as well as the bytes here, and is a follow-up rather than part of ACL transport.
225#[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
233/// Conservative byte budget for a single `DirectoryManifestChunk`. Well under the control
234/// stream's 8 MiB `LengthDelimitedCodec` frame limit, leaving ample margin for the message
235/// envelope and the worst-case final entry (a single ~`PATH_MAX` name).
236pub const MANIFEST_CHUNK_BYTE_BUDGET: usize = 4 * 1024 * 1024;
237
238/// Conservative serialized-size estimate for one `ExistingEntry`: the variable-length name plus a
239/// fixed allowance covering `is_file` + `Metadata` + `size` + per-entry framing overhead. Used
240/// only to bound chunk sizes, so over-estimating (smaller, safer chunks) is fine.
241fn estimate_entry_size(entry: &ExistingEntry) -> usize {
242    entry.name.as_os_str().len() + 64
243}
244
245/// Split a directory manifest into chunks each estimated to stay within `byte_budget`, so every
246/// `DirectoryManifestChunk` frame fits under the control stream's frame limit. A single entry
247/// larger than the budget still gets its own chunk (it cannot be split further); with the 4 MiB
248/// budget versus a worst-case ~4 KiB path, a chunk never approaches the 8 MiB frame limit.
249/// `chunk_manifest(v, b).concat() == v` for any `v` (no entries lost or reordered).
250pub 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/// File header sent on unidirectional streams, followed by raw file data.
270#[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/// Wrapper that includes size for comparison purposes.
280#[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/// Messages sent from source to destination on the control stream.
314#[derive(Debug, Deserialize, Serialize)]
315pub enum SourceMessage {
316    /// Begin a directory before submitting its children. Final metadata waits for End.
317    DirectoryBegin {
318        src: std::path::PathBuf,
319        dst: std::path::PathBuf,
320        metadata: Metadata,
321        is_root: bool,
322        /// Whether to retain this directory if no children remain after filtering.
323        keep_if_empty: bool,
324        /// Lifetime admission charged before Begin, independently of Ready.
325        admission: DirectoryClass,
326    },
327    /// Seal discovery with the number of admitted direct-child obligations.
328    DirectoryEnd {
329        src: std::path::PathBuf,
330        dst: std::path::PathBuf,
331        entry_count: usize,
332    },
333    /// Create symlink with metadata.
334    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    /// Signal that all directories and symlinks have been sent.
342    /// Required before destination can send `DestinationDone`.
343    /// `has_root_item` indicates whether a root file/directory/symlink will be sent.
344    /// When false (dry-run or filtered root), destination can mark root as complete.
345    DiscoveryComplete { has_root_item: bool },
346    /// Notify destination that a file failed to send.
347    /// Counts as a processed entry for the parent directory's completion tracking.
348    FileSkipped {
349        src: std::path::PathBuf,
350        dst: std::path::PathBuf,
351    },
352    /// Notify destination that the source skipped sending a file because the destination
353    /// already holds a matching entry (per the directory manifest). Counts as a processed
354    /// entry for the parent directory and as `files_unchanged` (the destination is the
355    /// authority for that count). The control-stream sibling of `FileSkipped`.
356    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/// Messages sent from destination to source on the control stream.
369#[derive(Clone, Debug, Deserialize, Serialize)]
370pub enum DestinationMessage {
371    /// Carry a chunk of the (reused) destination directory's pre-existing-entry manifest, used
372    /// by the source to skip transferring identical files. A directory's manifest is split into
373    /// one or more chunks (each well under the control stream's frame limit) and ALL of them are
374    /// sent BEFORE the directory's `DirectoryReady`; the control stream is FIFO, so the source
375    /// has the complete manifest by the time it sees `DirectoryReady`. No chunks are sent for a
376    /// freshly-created directory, when neither `--overwrite` nor `--ignore-existing` is active, or
377    /// when the directory exceeds the manifest cap (see `RcpdConfig::overwrite_manifest_max_entries`).
378    DirectoryManifestChunk {
379        dst: std::path::PathBuf,
380        entries: Vec<ExistingEntry>,
381    },
382    /// Confirm readiness to receive files, after all manifest chunks for this directory.
383    DirectoryReady {
384        src: std::path::PathBuf,
385        dst: std::path::PathBuf,
386    },
387    /// Reject a Begin, settling its parent slot and releasing source readiness credit.
388    /// Every Begin receives exactly one Ready or Skipped unless the session aborts.
389    DirectorySkipped {
390        src: std::path::PathBuf,
391        dst: std::path::PathBuf,
392    },
393    /// Return directory lifetime admission after all held descriptors and rollback owners close.
394    DirectoryReleased {
395        src: std::path::PathBuf,
396        dst: std::path::PathBuf,
397    },
398    /// Signal destination has finished all operations.
399    /// Initiates graceful shutdown via stream closure.
400    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    /// Preview mode must be known before startup descriptor admission and match the role hello.
416    pub preview_only: bool,
417    pub max_workers: usize,
418    pub max_blocking_threads: usize,
419    /// File-like work policy for this daemon's version-sensitive spawn contract.
420    pub files_in_flight: RcpdFilesInFlight,
421    pub ops_throttle: usize,
422    pub iops_throttle: usize,
423    pub chunk_size: usize,
424    /// Adaptive metadata-ops throttle settings, propagated from the
425    /// master's `--auto-meta-*` flags. `None` means the feature is off on
426    /// this rcpd instance.
427    pub auto_meta: Option<common::AutoMetaThrottleConfig>,
428    /// Mirror of master's --auto-meta-histogram flag.
429    pub auto_meta_histogram: bool,
430    /// Mirror of master's --auto-meta-histogram-log path. Each rcpd
431    /// suffixes its own trace identifier so the master and rcpds don't
432    /// collide on a localhost run.
433    pub auto_meta_histogram_log: Option<String>,
434    /// Mirror of master's --auto-meta-histogram-interval.
435    pub auto_meta_histogram_interval: std::time::Duration,
436    // common::copy::Settings
437    pub dereference: bool,
438    /// Mirror of master's --require-toctou-safe flag: arms strict operand
439    /// resolution (openat2 RESOLVE_NO_SYMLINKS root opens) on the rcpd side.
440    pub require_toctou_safe: bool,
441    pub overwrite: bool,
442    pub overwrite_compare: String,
443    /// Cap on pre-existing entries put into a directory's overwrite/ignore-existing manifest.
444    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    /// Port ranges for TCP connections (e.g., "8000-8999,9000-9999")
450    pub port_ranges: Option<String>,
451    pub progress: bool,
452    pub progress_delay: Option<String>,
453    pub remote_copy_conn_timeout_sec: u64,
454    /// Mirror of master's --remote-keepalive-sec: the liveness budget for every rcp TCP
455    /// connection this rcpd establishes or accepts. Without propagation the master would
456    /// recover from a vanished host while both rcpds keep hanging.
457    pub remote_keepalive_sec: u64,
458    /// Network profile for buffer sizing
459    pub network_profile: crate::NetworkProfile,
460    /// Buffer size for file transfers (defaults to profile-specific value)
461    pub buffer_size: Option<usize>,
462    /// Maximum retained receiver scratch per data connection; defaults to min(chunk, 2 MiB).
463    /// Zero disables retention without changing I/O chunk sizes.
464    pub buffer_retention_limit: Option<usize>,
465    /// Connection ceiling passed to this daemon. The automatic source receives configured `M`;
466    /// negotiated source/destination configurations receive effective `E`.
467    pub max_connections: usize,
468    /// Multiplier for pending file writes (max pending = max_connections × multiplier)
469    pub pending_writes_multiplier: usize,
470    /// Chrome trace output prefix for profiling
471    pub chrome_trace_prefix: Option<String>,
472    /// Aggregate scope timing output prefix, local to each daemon host.
473    pub timings_prefix: Option<String>,
474    /// Include detailed per-file timing scopes.
475    pub timings_detail: bool,
476    /// Flamegraph output prefix for profiling
477    pub flamegraph_prefix: Option<String>,
478    /// Log level for profiling (default: trace when profiling is enabled)
479    pub profile_level: Option<String>,
480    /// Enable tokio-console
481    pub tokio_console: bool,
482    /// Port for tokio-console server
483    pub tokio_console_port: Option<u16>,
484    /// Enable TLS encryption (default: true)
485    pub encryption: bool,
486    /// Master's certificate fingerprint for client authentication (when encryption enabled)
487    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        // network profile
568        args.push(format!("--network-profile={}", self.network_profile));
569        // tcp tuning (only if set)
570        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        // profiling options (only add --profile-level when profiling is enabled)
582        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        // propagate the adaptive metadata-ops throttle settings to rcpd so a
615        // remote copy uses the same control law as the master-side tool.
616        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        // Only forward histogram flags when there's a log path: the panel-
647        // only flag (--auto-meta-histogram) makes rcpd pay the synchronous
648        // accumulator lock cost on every probe, but rcpd's panel never
649        // reaches the user (the master's remote-progress renderer doesn't
650        // read the rcpd histogram registry). The log path is different —
651        // it produces a concrete artifact on the rcpd's host that the user
652        // can collect after the run.
653        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    /// true for tracing/progress connection, false for control connection
694    pub is_tracing: bool,
695}
696
697/// TLS certificate fingerprint (SHA-256 of DER-encoded certificate).
698pub type CertFingerprint = [u8; 32];
699
700/// What EXTENDED metadata the SOURCE must read, beyond the `stat` it already does.
701///
702/// Two of the three fields are per-entry reads whose bytes are sent; the third buys one read on the
703/// ROOT whose only product is a log line. All three answer the same question — what may the source
704/// spend an xattr syscall on — so with every field false the source issues none, EXCEPT under
705/// `--require-toctou-safe`: that flag arms the root notice from the source's own mirrored copy of
706/// it rather than from here, so a strict run still pays the one root `listxattr` on an all-false
707/// capture. Nothing per-entry is reachable that way — only `file_acl`/`dir_acl` open that door.
708///
709/// Carried in [`MasterHello::Source`] because the source otherwise has no way to know: only
710/// [`MasterHello::Destination`] carries `preserve`, so without this the source would have to probe
711/// unconditionally and every remote copy — including every one that does not want ACLs — would pay
712/// a syscall per entry that `stat` cannot fold in. That cost is the whole reason `acl` is opt-in.
713///
714/// Deliberately NOT the whole `preserve` struct, and named for what it is. The source decides only
715/// what to READ; the destination remains the sole authority on what is APPLIED. Handing the source
716/// a `preserve` would invite a later reader to act on, say, `preserve.file.mode_mask` source-side,
717/// which would be a bug. Every field [`MasterHello::Source`] already carries (`filter`, `dry_run`)
718/// is of this same "what to read/send" kind. The name leaves room for an `-X`-style xattr option to
719/// land here rather than growing another field.
720#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
721pub struct ExtendedMetadataCapture {
722    /// Read each source FILE's `system.posix_acl_access`.
723    pub file_acl: bool,
724    /// Read each source DIRECTORY's access AND default ACLs.
725    pub dir_acl: bool,
726    /// Probe the source ROOT once for a POSIX ACL, so the source can say that this copy will not
727    /// carry it across (see [`common::safedir::RootAclNotice`]).
728    ///
729    /// Independent of the two above: it is armed by the master's `preserve` asking for metadata
730    /// fidelity AT ALL, and disarmed by a copy that asked for none — the reads above are armed by
731    /// `preserve` asking for `acl` specifically, which is the case where there is nothing to warn
732    /// about. A run at the shipped default sets all three to false and the source touches no xattr.
733    pub root_acl_notice: bool,
734}
735
736impl ExtendedMetadataCapture {
737    /// What a copy preserving `preserve` requires the source to read.
738    ///
739    /// The ONE derivation, called at the single master site that also sends `preserve` to the
740    /// destination, so the two cannot disagree. That matters: the destination treats an all-`None`
741    /// [`Metadata::acls`] as "the source had none, so CLEAR", so a capture that said `false` while
742    /// the destination's `preserve` said `true` would silently strip every ACL instead of copying
743    /// it. Symlinks are absent by construction — the kernel has no symlink ACL, and the settings
744    /// parser rejects `l:acl`.
745    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    /// The source's view of the notice, reassembled from what crossed the wire.
756    ///
757    /// `--require-toctou-safe` is absent here on purpose: it reaches the source `rcpd` as its own
758    /// mirrored flag and is read from the process-global strict state, so it arms the notice on the
759    /// host that actually runs the probe rather than travelling twice.
760    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        /// Destination's TLS certificate fingerprint (None if encryption disabled)
775        dest_cert_fingerprint: Option<CertFingerprint>,
776        /// Filter settings for include/exclude patterns (source-side filtering)
777        filter: Option<common::filter::FilterSettings>,
778        /// Dry-run mode for previewing operations
779        dry_run: Option<common::config::DryRunMode>,
780        /// Extended metadata the source must read per entry (currently: POSIX ACLs). When every
781        /// field is false the source issues no xattr syscall at all.
782        capture: ExtendedMetadataCapture,
783    },
784    Destination {
785        /// TCP address for control connection to source
786        source_control_addr: std::net::SocketAddr,
787        /// TCP address for data connections to source
788        source_data_addr: std::net::SocketAddr,
789        server_name: String,
790        preserve: common::preserve::Settings,
791        /// Source's TLS certificate fingerprint (None if encryption disabled)
792        source_cert_fingerprint: Option<CertFingerprint>,
793        /// Preview-only operation; the source does not accept data connections.
794        dry_run: bool,
795    },
796}
797
798#[derive(Clone, Debug, Deserialize, Serialize)]
799pub struct SourceMasterHello {
800    /// TCP address for control connection (bidirectional messages)
801    pub control_addr: std::net::SocketAddr,
802    /// TCP address for data connections (file transfers)
803    pub data_addr: std::net::SocketAddr,
804    pub server_name: String,
805}
806
807// re-export RuntimeStats from common for convenience
808pub 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        // a tiny budget forces many chunks (each entry estimate is name.len() + 64 ≈ ~78 bytes)
865        let chunks = chunk_manifest(entries.clone(), 256);
866        assert!(
867            chunks.len() > 1,
868            "tiny budget should produce multiple chunks"
869        );
870        // frame-safety property: every multi-entry chunk stays within budget, so a chunk frame
871        // never approaches the control stream's frame limit
872        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        // reassembly invariant: concat preserves every entry, in order, with nothing lost
879        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        // budget smaller than a single entry: each still lands in its own chunk (never dropped).
889        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        // a realistically large directory manifest (more than two budgets' worth) must split into
898        // multiple frames with the PRODUCTION budget — not just an artificially tiny one — so a
899        // change to the budget or to `estimate_entry_size` that breaks chunking at real scale is
900        // caught. built in memory (no files), so it stays a fast unit test.
901        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        // every multi-entry chunk stays within the real budget (frame-safety)
913        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        // reassembly invariant at production scale: concat preserves every entry, in order
923        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        // the bytes must survive serialization UNCHANGED and in order: POSIX.1e requires canonical
938        // entry order and the destination kernel rejects anything else with EINVAL, so any
939        // re-encoding on the way through would fail at `fsetxattr` rather than silently.
940        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        // through the same codec the streams use, so this pins the real wire behavior
947        let bytes = bitcode::serialize(&meta).unwrap();
948        let back: Metadata = bitcode::deserialize(&bytes).unwrap();
949        // and the round trip reproduces the applier-side shape exactly
950        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        // neither `From` impl has an fd to probe, so both must leave the ACLs Unknown rather than
962        // guess — a site that should carry ACLs makes a visible `with_acls` call instead. Unknown
963        // tells the destination to leave the destination entry's ACLs alone; only a visible
964        // capture may produce the all-`None` CLEAR request.
965        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        // Captured-with-both-None is distinct from Unknown: it is the authoritative "the source
972        // has no ACL", which the destination applies by REMOVING the attributes.
973        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        // the one derivation: a capture that said `false` while the destination's `preserve` said
982        // `true` would make every entry arrive with all-`None` ACLs, which the destination reads as
983        // "clear" — stripping ACLs instead of copying them. Pinned per type, since the two flags are
984        // independent.
985        assert_eq!(
986            ExtendedMetadataCapture::for_preserve(&common::preserve::preserve_all_with_acls()),
987            ExtendedMetadataCapture {
988                file_acl: true,
989                dir_acl: true,
990                // armed by the run asking for preservation, but the per-kind flags above then turn
991                // the probe away: there is nothing to warn about once both kinds are carried across
992                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        // the whole point of the notice gate: a remote copy left at the shipped default must not
1021        // make the source touch a single xattr, root probe included
1022        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        // the source has no `preserve` of its own, so the notice it acts on is rebuilt from the
1031        // wire; a field crossed over here would silence or misdirect the probe on the far host
1032        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    // an rcpd that does not get the budget keeps hanging on a vanished peer while the master
1250    // recovers — which looks fixed and is worse than today's symmetric hang
1251    #[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        // 0 disables keepalive and must travel as faithfully as any other value
1264        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        // throttle-specific flags must be absent when auto_meta is None
1287        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        // histogram flag, log, and interval must all be absent when histograms are off
1309        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        // Critical for backward compatibility: existing rcpd binaries
1355        // built without histogram support reject --auto-meta-histogram-*
1356        // flags, so we must not emit them on every remote copy.
1357        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        // Panel-only --auto-meta-histogram is intentionally NOT forwarded
1372        // to rcpd: the panel never reaches the user (no plumbing in remote
1373        // progress), and forwarding would just add per-probe lock cost.
1374        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; // panel-only off
1390        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        // The bare panel flag is NOT pushed; the log flag at parse time on
1402        // rcpd already implies the accumulator pipeline.
1403        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}