Skip to main content

common/
cli.rs

1//! Common CLI arguments shared by every RCP binary.
2//!
3//! Each binary flattens [`CommonArgs`] into its own clap struct via
4//! `#[command(flatten)]`. Tool-specific arguments live in the binary itself.
5//!
6//! Fields intentionally NOT in this struct, so each binary can document them
7//! accurately:
8//! - `chunk_size` — rcp/rcpd parse as `bytesize::ByteSize` (e.g. "16MiB"),
9//!   others as bare `u64`.
10//! - `summary` — rcpd streams results to the master and never prints a summary.
11//! - `quiet` — rcmp's `--quiet` also suppresses stdout differences (not just
12//!   error output), so its help text differs from the other tools.
13
14/// Shared help for the file-like operation concurrency setting.
15pub const FILES_IN_FLIGHT_HELP: &str = "Maximum concurrent file-like operations. Local automatic defaults resolve from available CPU parallelism on this host, with a floor of 4. Use a positive integer for a finite ceiling or 'unlimited' to remove the user ceiling; lower internal safety ceilings may still apply. This applies to file copy, link, comparison, removal, chmod, and generation work.";
16
17#[derive(Debug, Clone, clap::Args)]
18pub struct CommonArgs {
19    // Progress & output
20    /// Show progress
21    #[arg(long, help_heading = "Progress & output")]
22    pub progress: bool,
23    /// Set the type of progress display
24    ///
25    /// If specified, --progress flag is implied.
26    #[arg(long, value_name = "TYPE", help_heading = "Progress & output")]
27    pub progress_type: Option<crate::ProgressType>,
28    /// Set delay between progress updates
29    ///
30    /// Default is 200ms for interactive mode (`ProgressBar`) and 10s for non-interactive
31    /// mode (`TextUpdates`). If specified, --progress flag is implied. Accepts
32    /// human-readable durations like "200ms", "10s", "5min".
33    #[arg(long, value_name = "DELAY", help_heading = "Progress & output")]
34    pub progress_delay: Option<String>,
35    /// Verbose level (implies "summary"): -v INFO / -vv DEBUG / -vvv TRACE (default: ERROR)
36    #[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count, help_heading = "Progress & output")]
37    pub verbose: u8,
38    /// Write aggregate elapsed-scope timings to per-process JSON files
39    ///
40    /// The prefix is expanded with tool/role, hostname, PID and timestamp. Remote
41    /// daemons write on their own hosts. Overlapping scope durations are cumulative,
42    /// not percentages of command wall time. This also works with --quiet.
43    #[arg(long, value_name = "PREFIX", help_heading = "Profiling")]
44    pub timings: Option<String>,
45    /// Include file, metadata, and tracker scopes in timing summaries and elapsed-scope traces
46    #[arg(long, help_heading = "Profiling")]
47    pub timings_detail: bool,
48    // Performance & throttling
49    /// Throttle the number of operations per second (0 = no throttle)
50    #[arg(
51        long,
52        default_value = "0",
53        value_name = "N",
54        help_heading = "Performance & throttling"
55    )]
56    pub ops_throttle: usize,
57    /// Limit I/O operations per second (0 = no throttle)
58    ///
59    /// Requires --chunk-size to calculate I/O operations per file: ((`file_size` - 1) / `chunk_size`) + 1
60    #[arg(
61        long,
62        default_value = "0",
63        value_name = "N",
64        help_heading = "Performance & throttling"
65    )]
66    pub iops_throttle: usize,
67    /// Maximum concurrent file-like operations.
68    #[arg(long, value_name = "N|unlimited", value_parser = parse_files_in_flight_limit,
69          help = FILES_IN_FLIGHT_HELP,
70          help_heading = "Performance & throttling",
71          conflicts_with = "max_open_files")]
72    pub max_files_in_flight: Option<crate::ConcurrencyLimit>,
73    #[arg(
74        long,
75        value_name = "N",
76        hide = true,
77        conflicts_with = "max_files_in_flight"
78    )]
79    pub max_open_files: Option<usize>,
80    // Advanced settings
81    /// Number of worker threads (0 = number of CPU cores)
82    #[arg(
83        long,
84        default_value = "0",
85        value_name = "N",
86        help_heading = "Advanced settings"
87    )]
88    pub max_workers: usize,
89    /// Number of blocking worker threads (0 = Tokio default of 512)
90    #[arg(
91        long,
92        default_value = "0",
93        value_name = "N",
94        help_heading = "Advanced settings"
95    )]
96    pub max_blocking_threads: usize,
97    // Congestion control (experimental, opt-in)
98    /// Enable adaptive metadata-ops throttling (latency-ratio controller)
99    #[arg(long, help_heading = "Congestion control")]
100    pub auto_meta_throttle: bool,
101    /// Initial concurrency window for adaptive metadata throttle
102    #[arg(
103        long,
104        default_value = "1",
105        value_name = "N",
106        help_heading = "Congestion control"
107    )]
108    pub auto_meta_initial_cwnd: u32,
109    /// Minimum concurrency window (floor below which cwnd cannot shrink)
110    #[arg(
111        long,
112        default_value = "1",
113        value_name = "N",
114        help_heading = "Congestion control (advanced)"
115    )]
116    pub auto_meta_min_cwnd: u32,
117    /// Maximum concurrency window (ceiling on adaptive growth)
118    #[arg(
119        long,
120        default_value = "4096",
121        value_name = "N",
122        help_heading = "Congestion control"
123    )]
124    pub auto_meta_max_cwnd: u32,
125    /// Latency ratio below which cwnd grows (current / baseline).
126    /// Default 1.3, sized to sit just below the steady-state p10/p50
127    /// inter-quantile spread of typical metadata syscalls so the
128    /// controller climbs only when the spread compresses. `alpha` may
129    /// be set below 1.0 in passive matched mode (grow only when recent
130    /// is meaningfully faster than baseline). The natural scale depends
131    /// on the percentile pair: matched percentiles produce a steady-
132    /// state ratio of 1.0; cross percentiles produce a ratio above 1.0
133    /// set by the inter-quantile spread of the latency distribution.
134    #[arg(
135        long,
136        default_value = "1.3",
137        value_name = "F",
138        help_heading = "Congestion control (advanced)"
139    )]
140    pub auto_meta_alpha: f64,
141    /// Latency ratio above which cwnd shrinks. Default 1.8, sized to
142    /// sit above the steady-state p10/p50 spread so only genuine
143    /// queueing-driven tail growth triggers a backoff.
144    #[arg(
145        long,
146        default_value = "1.8",
147        value_name = "F",
148        help_heading = "Congestion control (advanced)"
149    )]
150    pub auto_meta_beta: f64,
151    /// Percentile (in `[0.0, 1.0)`) applied to the long-horizon window
152    /// to derive the baseline statistic. Default 0.1 (p10): paired with
153    /// the p50 current percentile this gives a cross-percentile ratio
154    /// whose steady-state level tracks the lower-half spread of the
155    /// per-syscall latency distribution and rises with queueing. With
156    /// matched percentiles (`baseline == current`) the steady-state
157    /// ratio sits near 1.0 instead.
158    #[arg(
159        long,
160        default_value = "0.1",
161        value_name = "F",
162        help_heading = "Congestion control (advanced)"
163    )]
164    pub auto_meta_baseline_percentile: f64,
165    /// Percentile (in `[0.0, 1.0)`) applied to the short-horizon window
166    /// to derive the current statistic. Default 0.5 (p50). Must be
167    /// `>= baseline percentile`. See `--auto-meta-baseline-percentile`.
168    #[arg(
169        long,
170        default_value = "0.5",
171        value_name = "F",
172        help_heading = "Congestion control (advanced)"
173    )]
174    pub auto_meta_current_percentile: f64,
175    /// How much to grow cwnd on each under-shoot tick
176    #[arg(
177        long,
178        default_value = "1",
179        value_name = "N",
180        help_heading = "Congestion control (advanced)"
181    )]
182    pub auto_meta_increase_step: u32,
183    /// How much to shrink cwnd on each over-shoot tick
184    #[arg(
185        long,
186        default_value = "1",
187        value_name = "N",
188        help_heading = "Congestion control (advanced)"
189    )]
190    pub auto_meta_decrease_step: u32,
191    /// Long-horizon sample window (e.g. "10s"). Drives the baseline
192    /// percentile; samples older than this are evicted on every tick.
193    #[arg(
194        long,
195        default_value = "10s",
196        value_name = "DUR",
197        help_heading = "Congestion control (advanced)"
198    )]
199    pub auto_meta_long_window: humantime::Duration,
200    /// Short-horizon sample window (e.g. "1s"). Drives the current-state
201    /// percentile; must be strictly less than `--auto-meta-long-window`.
202    #[arg(
203        long,
204        default_value = "1s",
205        value_name = "DUR",
206        help_heading = "Congestion control (advanced)"
207    )]
208    pub auto_meta_short_window: humantime::Duration,
209    /// Control-loop tick interval (e.g. "50ms")
210    #[arg(
211        long,
212        default_value = "50ms",
213        value_name = "DUR",
214        help_heading = "Congestion control (advanced)"
215    )]
216    pub auto_meta_tick_interval: humantime::Duration,
217    /// Enable in-memory HDR latency histograms per (side, op). Implies
218    /// `--auto-meta-throttle`. Adds a distribution panel beneath the
219    /// existing one-line-per-controller summary in the progress display.
220    #[arg(long, help_heading = "Congestion control")]
221    pub auto_meta_histogram: bool,
222    /// Write a binary log of per-(side, op) HDR histograms to the given
223    /// path. The file is truncated if it already exists — rename or move
224    /// logs you want to keep across runs. Format documented in
225    /// `docs/congestion_control.md`. Implies `--auto-meta-histogram` and
226    /// `--auto-meta-throttle`.
227    #[arg(long, value_name = "PATH", help_heading = "Congestion control")]
228    pub auto_meta_histogram_log: Option<std::path::PathBuf>,
229    /// Snapshot cadence for the histogram logger (e.g. "1s"). Drives both
230    /// the panel refresh rate and the log-file record interval. Range
231    /// `[100ms, 60s]`.
232    #[arg(
233        long,
234        default_value = "1s",
235        value_name = "DUR",
236        help_heading = "Congestion control"
237    )]
238    pub auto_meta_histogram_interval: humantime::Duration,
239}
240
241impl CommonArgs {
242    /// Build the shared tracing configuration for a local tool.
243    #[must_use]
244    pub fn tracing_config(&self, identifier: &str) -> crate::TracingConfig {
245        crate::TracingConfig {
246            timings_prefix: self.timings.clone(),
247            timings_detail: self.timings_detail,
248            ..crate::TracingConfig::local(identifier)
249        }
250    }
251    #[must_use]
252    pub fn resolve_files_in_flight(&self) -> crate::ResolvedFilesInFlight {
253        match (self.max_files_in_flight, self.max_open_files) {
254            (Some(value), None) => crate::ResolvedFilesInFlight::explicit_limit(value),
255            (None, Some(value)) => crate::ResolvedFilesInFlight::legacy(value),
256            (None, None) => crate::ResolvedFilesInFlight::automatic(),
257            (Some(_), Some(_)) => unreachable!("clap rejects conflicting file limits"),
258        }
259    }
260    /// Build a [`crate::OutputConfig`]. `quiet` and `print_summary` are
261    /// supplied by the caller (each binary owns its own `--quiet` and
262    /// `--summary` flags so it can document binary-specific semantics).
263    #[must_use]
264    pub fn output_config(&self, quiet: bool, print_summary: bool) -> crate::OutputConfig {
265        crate::OutputConfig {
266            quiet,
267            verbose: self.verbose,
268            print_summary,
269            ..Default::default()
270        }
271    }
272    /// Build a [`crate::RuntimeConfig`] from these args.
273    #[must_use]
274    pub fn runtime_config(&self) -> crate::RuntimeConfig {
275        crate::RuntimeConfig {
276            max_workers: self.max_workers,
277            max_blocking_threads: self.max_blocking_threads,
278        }
279    }
280    /// Build a [`crate::ThrottleConfig`]. `chunk_size` has different parser types per binary.
281    #[must_use]
282    pub fn throttle_config(
283        &self,
284        files_in_flight: crate::ResolvedFilesInFlight,
285        chunk_size: u64,
286    ) -> crate::ThrottleConfig {
287        let auto_meta_implied = self.auto_meta_throttle
288            || self.auto_meta_histogram
289            || self.auto_meta_histogram_log.is_some();
290        let auto_meta = auto_meta_implied.then(|| crate::AutoMetaThrottleConfig {
291            initial_cwnd: self.auto_meta_initial_cwnd,
292            min_cwnd: self.auto_meta_min_cwnd,
293            max_cwnd: self.auto_meta_max_cwnd,
294            alpha: self.auto_meta_alpha,
295            beta: self.auto_meta_beta,
296            increase_step: self.auto_meta_increase_step,
297            decrease_step: self.auto_meta_decrease_step,
298            baseline_percentile: self.auto_meta_baseline_percentile,
299            current_percentile: self.auto_meta_current_percentile,
300            long_window: self.auto_meta_long_window.into(),
301            short_window: self.auto_meta_short_window.into(),
302            tick_interval: self.auto_meta_tick_interval.into(),
303        });
304        crate::ThrottleConfig {
305            files_in_flight,
306            apply_files_in_flight: true,
307            admission_policy: crate::AdmissionPolicy::Local,
308            ops_throttle: self.ops_throttle,
309            iops_throttle: self.iops_throttle,
310            chunk_size,
311            auto_meta,
312            histogram_enabled: self.auto_meta_histogram || self.auto_meta_histogram_log.is_some(),
313            histogram_log_path: self.auto_meta_histogram_log.clone(),
314            histogram_interval: self.auto_meta_histogram_interval.into(),
315        }
316    }
317    /// Returns true if any progress-related flag was set.
318    ///
319    /// `--auto-meta-histogram` implies progress because its sole purpose is
320    /// to render a live distribution panel. `--auto-meta-histogram-log` does
321    /// NOT imply progress — it writes to a file regardless of progress mode,
322    /// and forcing a display would be worse UX for users who only want the
323    /// file.
324    #[must_use]
325    pub fn progress_requested(&self) -> bool {
326        self.progress
327            || self.progress_type.is_some()
328            || self.progress_delay.is_some()
329            || self.auto_meta_histogram
330    }
331
332    /// Build user-facing [`crate::ProgressSettings`] when any progress flag was
333    /// set, else `None`. `kind` selects the tool-specific printer. For `rcp`'s
334    /// remote-master and `rcpd`'s remote progress modes, build `ProgressSettings`
335    /// directly instead of using this helper.
336    #[must_use]
337    pub fn user_progress_settings(
338        &self,
339        kind: crate::progress::LocalProgressKind,
340    ) -> Option<crate::ProgressSettings> {
341        if !self.progress_requested() {
342            return None;
343        }
344        Some(crate::ProgressSettings {
345            progress_type: crate::GeneralProgressType::User {
346                progress_type: self.progress_type.unwrap_or_default(),
347                kind,
348            },
349            progress_delay: self.progress_delay.clone(),
350        })
351    }
352}
353
354pub fn parse_positive_usize(value: &str) -> Result<std::num::NonZeroUsize, String> {
355    let value = value.parse::<usize>().map_err(|error| error.to_string())?;
356    std::num::NonZeroUsize::new(value).ok_or_else(|| "value must be at least 1".to_string())
357}
358
359pub fn parse_files_in_flight_limit(value: &str) -> Result<crate::ConcurrencyLimit, String> {
360    if value == "unlimited" {
361        return Ok(crate::ConcurrencyLimit::Unlimited);
362    }
363    parse_positive_usize(value).map(crate::ConcurrencyLimit::Limited)
364}
365
366pub fn parse_positive_u64(value: &str) -> Result<u64, String> {
367    let value = value.parse::<u64>().map_err(|error| error.to_string())?;
368    (value > 0)
369        .then_some(value)
370        .ok_or_else(|| "value must be at least 1".to_string())
371}
372
373#[cfg(test)]
374mod implies_tests {
375    use super::*;
376    use clap::Parser;
377    use std::num::NonZeroUsize;
378
379    #[derive(Debug, Parser)]
380    struct TestCli {
381        #[command(flatten)]
382        common: CommonArgs,
383    }
384
385    #[test]
386    fn max_files_in_flight_resolves_cli_sources() {
387        let explicit = TestCli::try_parse_from(["test", "--max-files-in-flight=1"])
388            .expect("positive max-files-in-flight must parse")
389            .common
390            .resolve_files_in_flight();
391        assert_eq!(
392            explicit,
393            crate::ResolvedFilesInFlight::explicit(NonZeroUsize::new(1).unwrap())
394        );
395        let explicit_unlimited =
396            TestCli::try_parse_from(["test", "--max-files-in-flight=unlimited"])
397                .expect("explicit unlimited max-files-in-flight must parse")
398                .common
399                .resolve_files_in_flight();
400        assert_eq!(
401            explicit_unlimited,
402            crate::ResolvedFilesInFlight::unlimited()
403        );
404        let automatic = TestCli::try_parse_from(["test"])
405            .expect("omitted max-files-in-flight must parse")
406            .common
407            .resolve_files_in_flight();
408        assert_eq!(automatic.source(), crate::FilesInFlightSource::Automatic);
409        let legacy_zero = TestCli::try_parse_from(["test", "--max-open-files=0"])
410            .expect("legacy zero must parse")
411            .common
412            .resolve_files_in_flight();
413        assert_eq!(legacy_zero.limit(), crate::ConcurrencyLimit::Unlimited);
414        assert_eq!(
415            legacy_zero.source(),
416            crate::FilesInFlightSource::DeprecatedMaxOpenFiles
417        );
418        let legacy_positive = TestCli::try_parse_from(["test", "--max-open-files=7"])
419            .expect("positive legacy value must parse")
420            .common
421            .resolve_files_in_flight();
422        assert_eq!(legacy_positive, crate::ResolvedFilesInFlight::legacy(7));
423    }
424
425    #[test]
426    fn max_files_in_flight_rejects_invalid_and_conflicting_values() {
427        let zero = TestCli::try_parse_from(["test", "--max-files-in-flight=0"])
428            .expect_err("zero max-files-in-flight must be rejected");
429        assert!(zero.to_string().contains("value must be at least 1"));
430        assert!(TestCli::try_parse_from(["test", "--max-files-in-flight=nope"]).is_err());
431        assert!(
432            TestCli::try_parse_from(["test", "--max-files-in-flight=1", "--max-open-files=1",])
433                .is_err()
434        );
435    }
436
437    #[test]
438    fn max_files_in_flight_help_stays_local_to_shared_tools() {
439        let help = TestCli::try_parse_from(["test", "--help"])
440            .expect_err("help must stop clap parsing")
441            .to_string();
442        assert!(help.contains(
443            "Local automatic defaults resolve from available CPU parallelism on this host"
444        ));
445        assert!(
446            !help.contains("source rcpd"),
447            "shared CLI help must not describe remote negotiation: {help}"
448        );
449    }
450
451    #[test]
452    fn long_help_only_advertises_max_files_in_flight() {
453        let help = TestCli::try_parse_from(["test", "--help"])
454            .expect_err("help must stop clap parsing")
455            .to_string();
456        assert!(help.contains("--max-files-in-flight"));
457        assert!(!help.contains("--max-open-files"));
458    }
459
460    #[test]
461    fn auto_meta_histogram_implies_throttle_at_cli() {
462        let cli = TestCli::parse_from(["test", "--auto-meta-histogram"]);
463        let throttle = cli
464            .common
465            .throttle_config(cli.common.resolve_files_in_flight(), 0);
466        assert!(
467            throttle.auto_meta.is_some(),
468            "histogram flag must imply auto_meta"
469        );
470        assert!(throttle.histogram_enabled);
471    }
472
473    #[test]
474    fn auto_meta_histogram_log_implies_throttle_at_cli() {
475        let cli = TestCli::parse_from(["test", "--auto-meta-histogram-log", "/tmp/x.hdr"]);
476        let throttle = cli
477            .common
478            .throttle_config(cli.common.resolve_files_in_flight(), 0);
479        assert!(
480            throttle.auto_meta.is_some(),
481            "histogram-log flag must imply auto_meta"
482        );
483        assert!(throttle.histogram_log_path.is_some());
484    }
485
486    #[test]
487    fn no_auto_meta_flags_means_no_throttle() {
488        let cli = TestCli::parse_from(["test"]);
489        let throttle = cli
490            .common
491            .throttle_config(cli.common.resolve_files_in_flight(), 0);
492        assert!(throttle.auto_meta.is_none());
493        assert!(!throttle.histogram_enabled);
494    }
495
496    /// `--auto-meta-histogram` (panel-only) sets `auto_meta_throttle = false`.
497    ///
498    /// The rcp binary uses this distinction when building `RcpdConfig`: it
499    /// gates `RcpdConfig::auto_meta` on `auto_meta_throttle || histogram_log
500    /// .is_some()`, so that the panel-only flag does NOT silently enable the
501    /// throttle pipeline on remote daemons.  This test pins that distinction
502    /// at the `CommonArgs` level so a future refactor cannot accidentally
503    /// collapse the two flags.
504    #[test]
505    fn panel_flag_does_not_set_explicit_throttle_field() {
506        let cli = TestCli::parse_from(["test", "--auto-meta-histogram"]);
507        // `throttle_config()` returns `auto_meta = Some(...)` because the
508        // panel needs the throttle pipeline locally — that's intentional.
509        assert!(
510            cli.common
511                .throttle_config(cli.common.resolve_files_in_flight(), 0)
512                .auto_meta
513                .is_some()
514        );
515        // But the *explicit* throttle field must stay false so the rcp binary
516        // can distinguish "panel only" from "user explicitly asked for throttle".
517        assert!(
518            !cli.common.auto_meta_throttle,
519            "--auto-meta-histogram must not set auto_meta_throttle"
520        );
521        // And no log path either.
522        assert!(cli.common.auto_meta_histogram_log.is_none());
523    }
524
525    #[test]
526    fn auto_meta_histogram_implies_progress() {
527        let cli = TestCli::parse_from(["test", "--auto-meta-histogram"]);
528        assert!(
529            cli.common.progress_requested(),
530            "--auto-meta-histogram alone must imply progress so the panel actually renders",
531        );
532    }
533
534    #[test]
535    fn auto_meta_histogram_log_does_not_imply_progress() {
536        // the log file writes regardless of progress; user can opt in to
537        // progress separately. don't force it on them.
538        let cli = TestCli::parse_from(["test", "--auto-meta-histogram-log", "/tmp/x.hdr"]);
539        assert!(
540            !cli.common.progress_requested(),
541            "--auto-meta-histogram-log alone should NOT imply progress",
542        );
543    }
544}