Skip to main content

common/
lib.rs

1//! Common utilities and types for RCP file operation tools
2//!
3//! This crate provides shared functionality used across all RCP tools (`rcp`, `rrm`, `rlink`, `rcmp`).
4//! It includes core operations (copy, remove, link, compare), progress reporting, metadata preservation, and runtime configuration.
5//!
6//! # Core Modules
7//!
8//! - [`mod@copy`] - File copying operations with metadata preservation and error handling
9//! - [`mod@rm`] - File removal operations
10//! - [`mod@link`] - Hard-linking operations
11//! - [`mod@cmp`] - File comparison operations (metadata-based)
12//! - [`mod@preserve`] - Metadata preservation settings and operations
13//! - [`mod@progress`] - Progress tracking and reporting
14//! - [`mod@filecmp`] - File metadata comparison utilities
15//! - [`mod@remote_tracing`] - Remote tracing support for distributed operations
16//!
17//! # Key Types
18//!
19//! ## `RcpdType`
20//!
21//! Identifies the role of a remote copy daemon:
22//! - `Source` - reads files from source host
23//! - `Destination` - writes files to destination host
24//!
25//! ## `ProgressType`
26//!
27//! Controls progress reporting display:
28//! - `Auto` - automatically choose based on terminal type
29//! - `ProgressBar` - animated progress bar (for interactive terminals)
30//! - `TextUpdates` - periodic text updates (for logging/non-interactive)
31//!
32//! # Progress Reporting
33//!
34//! The crate provides a global progress tracking system accessible via [`get_progress()`].
35//! Progress can be displayed in different formats depending on the execution context.
36//!
37//! Progress output goes to stderr, while logs go to stdout, allowing users to redirect logs to a file while still viewing interactive progress.
38//!
39//! # Runtime Configuration
40//!
41//! The [`run`] function provides a unified entry point for all RCP tools with support for:
42//! - Progress tracking and reporting
43//! - Logging configuration (quiet/verbose modes)
44//! - Resource limits (max workers, leaf-operation descriptor admission, throttling)
45//! - Tokio runtime setup
46//! - Remote tracing integration
47//!
48//! # Examples
49//!
50//! ## Basic Copy Operation
51//!
52//! ```rust,no_run
53//! use std::path::Path;
54//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
55//! let src = Path::new("/source");
56//! let dst = Path::new("/destination");
57//!
58//! let settings = common::copy::Settings {
59//!     reflink: Default::default(),
60//!     local_copy_handoff: Default::default(),
61//!     dereference: false,
62//!     fail_early: false,
63//!     overwrite: false,
64//!     overwrite_compare: Default::default(),
65//!     overwrite_filter: None,
66//!     ignore_existing: false,
67//!     chunk_size: 0,
68//!     skip_specials: false,
69//!     remote_copy_buffer_size: 0,
70//!     filter: None,
71//!     dry_run: None,
72//!     delete: None,
73//! };
74//! let preserve = common::preserve::preserve_none();
75//!
76//! let session = common::copy::CopySession::default();
77//! let summary = common::copy(&session, src, dst, &settings, &preserve).await?;
78//! println!("Copied {} files", summary.files_copied);
79//! # Ok(())
80//! # }
81//! ```
82//!
83//! ## Metadata Comparison
84//!
85//! ```rust,no_run
86//! use std::path::Path;
87//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
88//! let src = Path::new("/path1");
89//! let dst = Path::new("/path2");
90//!
91//! // output differences to stdout (use false for quiet mode)
92//! let log = common::cmp::LogWriter::new(None, true, common::cmp::OutputFormat::default()).await?;
93//! let settings = common::cmp::Settings {
94//!     fail_early: false,
95//!     exit_early: false,
96//!     expand_missing: false,
97//!     compare: Default::default(),
98//!     filter: None,
99//! };
100//!
101//! let summary = common::cmp(src, dst, &log, &settings).await?;
102//! println!("Comparison complete: {}", summary);
103//! # Ok(())
104//! # }
105//! ```
106
107use anyhow::Context;
108use std::io::IsTerminal;
109use tracing::instrument;
110
111mod auto_meta;
112pub mod chmod;
113pub mod cli;
114pub mod cmp;
115pub mod config;
116pub mod copy;
117pub mod copy_data;
118pub mod delete;
119pub mod dry_run;
120pub mod error;
121pub mod error_collector;
122pub mod filegen;
123pub mod filter;
124pub mod histogram_logger;
125pub mod histogram_panel;
126mod input_protection;
127pub mod link;
128pub mod observability;
129pub mod preserve;
130pub mod remote_tracing;
131pub mod rm;
132mod runtime_setup;
133pub mod safedir;
134mod settings_parse;
135pub mod task_scope;
136pub mod timing;
137pub mod version;
138
139pub mod filecmp;
140pub mod progress;
141mod testutils;
142pub mod toctou_check;
143pub mod walk;
144pub(crate) mod walk_driver;
145
146pub use config::{
147    AdmissionPolicy, AutoMetaThrottleConfig, ConcurrencyLimit, DryRunMode, DryRunWarnings,
148    FilesInFlightSource, MIN_DEFAULT_FILES_IN_FLIGHT, OutputConfig, ResolvedFilesInFlight,
149    RuntimeConfig, ThrottleConfig, TracingConfig,
150};
151// Re-export `Side` from the congestion crate so downstream binaries
152// (rcp, rrm, …) and integration tests can pass `common::Side::Source` /
153// `common::Side::Destination` to `walk::next_entry_probed` and friends
154// without taking a direct dependency on `congestion`.
155pub use congestion::{MetadataOp, Side};
156pub use progress::{RcpdProgressPrinter, SerializableProgress};
157// Re-export the runtime-stat / trace-filename helpers that moved into
158// `runtime_setup` so downstream binaries keep reaching them as
159// `common::collect_runtime_stats`, etc.
160pub use runtime_setup::{
161    EndpointAdmission, NOTICE_TARGET, RemoteResources, collect_runtime_stats,
162    generate_debug_log_filename, generate_trace_filename,
163};
164pub use settings_parse::{
165    parse_compare_settings, parse_metadata_cmp_settings, parse_preserve_settings,
166    validate_update_compare_vs_preserve,
167};
168
169// Define RcpdType in common since remote depends on common
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, enum_map::Enum)]
171pub enum RcpdType {
172    Source,
173    Destination,
174}
175
176impl std::fmt::Display for RcpdType {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        match self {
179            RcpdType::Source => write!(f, "source"),
180            RcpdType::Destination => write!(f, "destination"),
181        }
182    }
183}
184
185// Type alias for progress snapshots
186pub type ProgressSnapshot<T> = enum_map::EnumMap<RcpdType, T>;
187
188/// runtime statistics collected from a process (CPU time, memory usage)
189#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
190pub struct RuntimeStats {
191    /// user-mode CPU time in milliseconds
192    pub cpu_time_user_ms: u64,
193    /// kernel-mode CPU time in milliseconds
194    pub cpu_time_kernel_ms: u64,
195    /// peak resident set size in bytes
196    pub peak_rss_bytes: u64,
197}
198
199/// runtime stats collected from remote rcpd processes for display at the end of a remote copy
200#[derive(Debug, Default)]
201pub struct RemoteRuntimeStats {
202    pub source_host: String,
203    pub source_stats: RuntimeStats,
204    pub dest_host: String,
205    pub dest_stats: RuntimeStats,
206}
207
208/// checks if a host string refers to the local machine.
209/// returns true for `localhost`, `127.0.0.1`, `::1`, `[::1]`, or the actual hostname
210#[must_use]
211pub fn is_localhost(host: &str) -> bool {
212    if host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "[::1]" {
213        return true;
214    }
215    // check against actual hostname using gethostname
216    let mut buf = [0u8; 256];
217    // Safety: gethostname writes to buf and returns 0 on success
218    let result = unsafe { libc::gethostname(buf.as_mut_ptr() as *mut libc::c_char, buf.len()) };
219    if result == 0
220        && let Ok(hostname_cstr) = std::ffi::CStr::from_bytes_until_nul(&buf)
221        && let Ok(hostname) = hostname_cstr.to_str()
222        && host == hostname
223    {
224        return true;
225    }
226    false
227}
228
229pub(crate) static PROGRESS: std::sync::LazyLock<progress::Progress> =
230    std::sync::LazyLock::new(progress::Progress::new);
231pub(crate) static PBAR: std::sync::LazyLock<indicatif::ProgressBar> =
232    std::sync::LazyLock::new(indicatif::ProgressBar::new_spinner);
233pub(crate) static REMOTE_RUNTIME_STATS: std::sync::LazyLock<
234    std::sync::Mutex<Option<RemoteRuntimeStats>>,
235> = std::sync::LazyLock::new(|| std::sync::Mutex::new(None));
236static HISTOGRAM_LOGGER_CANCEL: std::sync::Mutex<Option<tokio::sync::watch::Sender<bool>>> =
237    std::sync::Mutex::new(None);
238static HISTOGRAM_LOGGER_HANDLE: std::sync::Mutex<Option<tokio::task::JoinHandle<()>>> =
239    std::sync::Mutex::new(None);
240
241pub(crate) fn store_logger_cancel(tx: tokio::sync::watch::Sender<bool>) {
242    *HISTOGRAM_LOGGER_CANCEL
243        .lock()
244        .expect("histogram logger cancel mutex poisoned") = Some(tx);
245}
246
247pub(crate) fn store_logger_handle(handle: tokio::task::JoinHandle<()>) {
248    *HISTOGRAM_LOGGER_HANDLE
249        .lock()
250        .expect("histogram logger handle mutex poisoned") = Some(handle);
251}
252
253fn take_logger_handle() -> Option<tokio::task::JoinHandle<()>> {
254    HISTOGRAM_LOGGER_HANDLE
255        .lock()
256        .expect("histogram logger handle mutex poisoned")
257        .take()
258}
259
260fn signal_logger_cancel() {
261    if let Some(tx) = HISTOGRAM_LOGGER_CANCEL
262        .lock()
263        .expect("histogram logger cancel mutex poisoned")
264        .take()
265        && let Err(err) = tx.send(true)
266    {
267        tracing::debug!("histogram-logger cancel send failed (already gone): {err:#}");
268    }
269}
270
271#[must_use]
272pub fn get_progress() -> &'static progress::Progress {
273    &PROGRESS
274}
275
276/// stores remote runtime stats for display at the end of a remote copy operation
277pub fn set_remote_runtime_stats(stats: RemoteRuntimeStats) {
278    *REMOTE_RUNTIME_STATS.lock().unwrap() = Some(stats);
279}
280
281struct ProgressTracker {
282    lock_cvar: std::sync::Arc<(std::sync::Mutex<bool>, std::sync::Condvar)>,
283    pbar_thread: Option<std::thread::JoinHandle<()>>,
284}
285
286#[derive(Copy, Clone, Debug, Default, clap::ValueEnum)]
287pub enum ProgressType {
288    #[default]
289    #[value(name = "auto", alias = "Auto")]
290    Auto,
291    #[value(name = "ProgressBar", alias = "progress-bar")]
292    ProgressBar,
293    #[value(name = "TextUpdates", alias = "text-updates")]
294    TextUpdates,
295}
296
297pub enum GeneralProgressType {
298    User {
299        progress_type: ProgressType,
300        kind: progress::LocalProgressKind,
301    },
302    Remote(tokio::sync::mpsc::UnboundedSender<remote_tracing::TracingMessage>),
303    RemoteMaster {
304        progress_type: ProgressType,
305        get_progress_snapshot:
306            Box<dyn Fn() -> ProgressSnapshot<SerializableProgress> + Send + 'static>,
307    },
308}
309
310impl std::fmt::Debug for GeneralProgressType {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        match self {
313            GeneralProgressType::User {
314                progress_type,
315                kind,
316            } => write!(f, "User(progress_type: {progress_type:?}, kind: {kind:?})"),
317            GeneralProgressType::Remote(_) => write!(f, "Remote(<sender>)"),
318            GeneralProgressType::RemoteMaster { progress_type, .. } => {
319                write!(
320                    f,
321                    "RemoteMaster(progress_type: {progress_type:?}, <function>)"
322                )
323            }
324        }
325    }
326}
327
328#[derive(Debug)]
329pub struct ProgressSettings {
330    pub progress_type: GeneralProgressType,
331    pub progress_delay: Option<String>,
332}
333
334fn progress_bar(
335    lock: &std::sync::Mutex<bool>,
336    cvar: &std::sync::Condvar,
337    delay_opt: &Option<std::time::Duration>,
338    kind: progress::LocalProgressKind,
339) {
340    let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
341    PBAR.set_style(
342        indicatif::ProgressStyle::with_template("{spinner:.cyan} {msg}")
343            .unwrap()
344            .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
345    );
346    let mut prog_printer = progress::make_local_printer(kind, &PROGRESS);
347    let mut is_done = lock.lock().unwrap();
348    loop {
349        PBAR.set_position(PBAR.position() + 1); // do we need to update?
350        let mut msg = prog_printer.print().unwrap();
351        msg.push_str(&observability::render_lines());
352        msg.push_str(&render_panel_from_registry());
353        PBAR.set_message(msg);
354        let result = cvar.wait_timeout(is_done, delay).unwrap();
355        is_done = result.0;
356        if *is_done {
357            break;
358        }
359    }
360    PBAR.finish_and_clear();
361}
362
363fn get_datetime_prefix() -> String {
364    chrono::Local::now()
365        .format("%Y-%m-%dT%H:%M:%S%.3f%:z")
366        .to_string()
367}
368
369fn text_updates(
370    lock: &std::sync::Mutex<bool>,
371    cvar: &std::sync::Condvar,
372    delay_opt: &Option<std::time::Duration>,
373    kind: progress::LocalProgressKind,
374) {
375    let delay = delay_opt.unwrap_or(std::time::Duration::from_secs(10));
376    let mut prog_printer = progress::make_local_printer(kind, &PROGRESS);
377    let mut is_done = lock.lock().unwrap();
378    loop {
379        eprintln!("=======================");
380        eprintln!(
381            "{}\n--{}{}{}",
382            get_datetime_prefix(),
383            prog_printer.print().unwrap(),
384            observability::render_lines(),
385            render_panel_from_registry(),
386        );
387        let result = cvar.wait_timeout(is_done, delay).unwrap();
388        is_done = result.0;
389        if *is_done {
390            break;
391        }
392    }
393}
394
395fn rcpd_updates(
396    lock: &std::sync::Mutex<bool>,
397    cvar: &std::sync::Condvar,
398    delay_opt: &Option<std::time::Duration>,
399    sender: tokio::sync::mpsc::UnboundedSender<remote_tracing::TracingMessage>,
400) {
401    tracing::debug!("Starting rcpd progress updates");
402    let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
403    let mut is_done = lock.lock().unwrap();
404    loop {
405        if remote_tracing::send_progress_update(&sender, &PROGRESS).is_err() {
406            // channel closed, receiver is done
407            tracing::debug!("Progress update channel closed, stopping progress updates");
408            break;
409        }
410        let result = cvar.wait_timeout(is_done, delay).unwrap();
411        is_done = result.0;
412        if *is_done {
413            break;
414        }
415    }
416}
417
418fn remote_master_updates<F>(
419    lock: &std::sync::Mutex<bool>,
420    cvar: &std::sync::Condvar,
421    delay_opt: &Option<std::time::Duration>,
422    get_progress_snapshot: F,
423    progress_type: ProgressType,
424) where
425    F: Fn() -> ProgressSnapshot<SerializableProgress> + Send + 'static,
426{
427    let interactive = match progress_type {
428        ProgressType::Auto => std::io::stderr().is_terminal(),
429        ProgressType::ProgressBar => true,
430        ProgressType::TextUpdates => false,
431    };
432    if interactive {
433        PBAR.set_style(
434            indicatif::ProgressStyle::with_template("{spinner:.cyan} {msg}")
435                .unwrap()
436                .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]),
437        );
438        let delay = delay_opt.unwrap_or(std::time::Duration::from_millis(200));
439        let mut printer = RcpdProgressPrinter::new();
440        let mut is_done = lock.lock().unwrap();
441        loop {
442            let progress_map = get_progress_snapshot();
443            let source_progress = &progress_map[RcpdType::Source];
444            let destination_progress = &progress_map[RcpdType::Destination];
445            PBAR.set_position(PBAR.position() + 1); // do we need to update?
446            let mut msg = printer
447                .print(source_progress, destination_progress)
448                .unwrap();
449            msg.push_str(&render_panel_from_registry());
450            PBAR.set_message(msg);
451            let result = cvar.wait_timeout(is_done, delay).unwrap();
452            is_done = result.0;
453            if *is_done {
454                break;
455            }
456        }
457        PBAR.finish_and_clear();
458    } else {
459        let delay = delay_opt.unwrap_or(std::time::Duration::from_secs(10));
460        let mut printer = RcpdProgressPrinter::new();
461        let mut is_done = lock.lock().unwrap();
462        loop {
463            let progress_map = get_progress_snapshot();
464            let source_progress = &progress_map[RcpdType::Source];
465            let destination_progress = &progress_map[RcpdType::Destination];
466            eprintln!("=======================");
467            eprintln!(
468                "{}\n--{}{}",
469                get_datetime_prefix(),
470                printer
471                    .print(source_progress, destination_progress)
472                    .unwrap(),
473                render_panel_from_registry(),
474            );
475            let result = cvar.wait_timeout(is_done, delay).unwrap();
476            is_done = result.0;
477            if *is_done {
478                break;
479            }
480        }
481    }
482}
483
484impl ProgressTracker {
485    pub fn new(progress_type: GeneralProgressType, delay_opt: Option<std::time::Duration>) -> Self {
486        let lock_cvar =
487            std::sync::Arc::new((std::sync::Mutex::new(false), std::sync::Condvar::new()));
488        let lock_cvar_clone = lock_cvar.clone();
489        let pbar_thread = std::thread::spawn(move || {
490            let (lock, cvar) = &*lock_cvar_clone;
491            match progress_type {
492                GeneralProgressType::Remote(sender) => {
493                    rcpd_updates(lock, cvar, &delay_opt, sender);
494                }
495                GeneralProgressType::RemoteMaster {
496                    progress_type,
497                    get_progress_snapshot,
498                } => {
499                    remote_master_updates(
500                        lock,
501                        cvar,
502                        &delay_opt,
503                        get_progress_snapshot,
504                        progress_type,
505                    );
506                }
507                GeneralProgressType::User {
508                    progress_type,
509                    kind,
510                } => {
511                    let interactive = match progress_type {
512                        ProgressType::Auto => std::io::stderr().is_terminal(),
513                        ProgressType::ProgressBar => true,
514                        ProgressType::TextUpdates => false,
515                    };
516                    if interactive {
517                        progress_bar(lock, cvar, &delay_opt, kind);
518                    } else {
519                        text_updates(lock, cvar, &delay_opt, kind);
520                    }
521                }
522            }
523        });
524        Self {
525            lock_cvar,
526            pbar_thread: Some(pbar_thread),
527        }
528    }
529}
530
531impl Drop for ProgressTracker {
532    fn drop(&mut self) {
533        let (lock, cvar) = &*self.lock_cvar;
534        let mut is_done = lock.lock().unwrap();
535        *is_done = true;
536        cvar.notify_one();
537        drop(is_done);
538        if let Some(pbar_thread) = self.pbar_thread.take() {
539            pbar_thread.join().unwrap();
540        }
541    }
542}
543
544pub async fn cmp(
545    src: &std::path::Path,
546    dst: &std::path::Path,
547    log: &cmp::LogWriter,
548    settings: &cmp::Settings,
549) -> Result<cmp::Summary, anyhow::Error> {
550    cmp::cmp(&PROGRESS, src, dst, log, settings).await
551}
552
553pub async fn copy(
554    session: &copy::CopySession,
555    src: &std::path::Path,
556    dst: &std::path::Path,
557    settings: &copy::Settings,
558    preserve: &preserve::Settings,
559) -> Result<copy::Summary, copy::Error> {
560    session
561        .copy(&PROGRESS, src, dst, settings, preserve, false)
562        .await
563}
564
565/// Execute an operand prepared before local batch dispatch.
566pub async fn copy_prepared(
567    prepared: copy::PreparedCopy,
568    preserve: &preserve::Settings,
569) -> Result<copy::Summary, copy::Error> {
570    prepared.copy(&PROGRESS, preserve, false).await
571}
572
573pub async fn rm(path: &std::path::Path, settings: &rm::Settings) -> Result<rm::Summary, rm::Error> {
574    rm::rm(&PROGRESS, path, settings).await
575}
576
577pub async fn chmod(
578    path: &std::path::Path,
579    settings: &chmod::Settings,
580) -> Result<chmod::Summary, chmod::Error> {
581    chmod::chmod(&PROGRESS, path, settings).await
582}
583
584pub async fn link(
585    src: &std::path::Path,
586    dst: &std::path::Path,
587    update: &Option<std::path::PathBuf>,
588    settings: &link::Settings,
589) -> Result<link::Summary, link::Error> {
590    let cwd = std::env::current_dir()
591        .with_context(|| "failed to get current working directory")
592        .map_err(|err| link::Error::new(err, link::Summary::default()))?;
593    link::link(&PROGRESS, &cwd, src, dst, update, settings, false).await
594}
595
596fn render_panel_from_registry() -> String {
597    let entries = observability::registered_histograms();
598    if entries.is_empty() {
599        return String::new();
600    }
601    let snapshots: Vec<hdrhistogram::Histogram<u64>> = entries
602        .iter()
603        .map(|e| (*e.snapshot_rx.borrow()).clone())
604        .collect();
605    let units: Vec<histogram_panel::PanelUnit> = entries
606        .iter()
607        .zip(snapshots.iter())
608        .map(|(e, snap)| histogram_panel::PanelUnit {
609            label: e.label,
610            histogram: snap,
611            interval: e.interval,
612        })
613        .collect();
614    histogram_panel::render_histogram_panel(&units)
615}
616
617/// Format one pre-tracing diagnostic, optionally as a machine-readable startup record.
618#[must_use]
619pub fn format_startup_diagnostic(prefix: Option<&str>, diagnostic: &str) -> String {
620    let one_line = diagnostic
621        .lines()
622        .map(str::trim)
623        .filter(|line| !line.is_empty())
624        .collect::<Vec<_>>()
625        .join(" ");
626    format!("{}{one_line}", prefix.unwrap_or_default())
627}
628
629fn print_startup_configuration_error(
630    startup_error_prefix: Option<&str>,
631    error: &impl std::fmt::Display,
632) {
633    eprintln!(
634        "{}",
635        format_startup_diagnostic(
636            startup_error_prefix,
637            &format!("Configuration error: {error:#}"),
638        )
639    );
640}
641
642/// Run an operation after startup, passing the endpoint admission installed for this runtime.
643///
644/// Setup failure reports its diagnostic without invoking the operation callback.
645#[instrument(skip(func))] // "func" is not Debug printable
646pub fn run<Fut, Summary, Error>(
647    progress: Option<ProgressSettings>,
648    output: OutputConfig,
649    runtime_config: RuntimeConfig,
650    throttle_config: ThrottleConfig,
651    tracing_config: TracingConfig,
652    func: impl FnOnce(EndpointAdmission) -> Fut,
653) -> Option<Summary>
654// we return an Option rather than a Result to indicate that callers of this function should NOT print the error
655where
656    Summary: std::fmt::Display,
657    Error: std::fmt::Display + std::fmt::Debug,
658    Fut: std::future::Future<Output = Result<Summary, Error>>,
659{
660    // force initialization of PROGRESS to set start_time at the beginning of the run
661    // (for remote master operations, PROGRESS is otherwise only accessed at the end in
662    // print_runtime_stats(), leading to near-zero walltime)
663    let _ = get_progress();
664    let OutputConfig {
665        quiet,
666        verbose,
667        print_summary,
668        suppress_runtime_stats,
669        startup_error_prefix,
670    } = output;
671    if let Err(error) = throttle_config.validate() {
672        print_startup_configuration_error(startup_error_prefix, &error);
673        return None;
674    }
675    // tracing guards must outlive the runtime so chrome/flame traces flush
676    // extract trace_identifier before install_tracing_subscriber consumes tracing_config
677    let trace_identifier = tracing_config.trace_identifier.clone();
678    if let Err(error) =
679        runtime_setup::validate_histogram_log_target(&throttle_config, &trace_identifier)
680    {
681        print_startup_configuration_error(startup_error_prefix, &error);
682        return None;
683    }
684    let mut tracing_guards =
685        match runtime_setup::install_tracing_subscriber(quiet, verbose, tracing_config) {
686            Ok(guards) => guards,
687            Err(error) => {
688                print_startup_configuration_error(startup_error_prefix, &error);
689                return None;
690            }
691        };
692    if let Some(warning) = throttle_config.deprecated_max_open_files_warning() {
693        tracing::warn!(target: NOTICE_TARGET, "{warning}");
694    }
695    let res = {
696        let (runtime, admission) =
697            match runtime_setup::build_tokio_runtime(&runtime_config, &throttle_config) {
698                Ok(runtime) => runtime,
699                Err(error) => {
700                    print_startup_configuration_error(startup_error_prefix, &error);
701                    return None;
702                }
703            };
704        runtime_setup::spawn_throttle_replenishers(&runtime, &throttle_config, &trace_identifier);
705        let res = {
706            let _progress_tracker = progress.map(|settings| {
707                tracing::debug!("Requesting progress updates {settings:?}");
708                let delay = settings.progress_delay.map(|delay_str| {
709                    humantime::parse_duration(&delay_str)
710                        .expect("Couldn't parse duration out of --progress-delay")
711                });
712                ProgressTracker::new(settings.progress_type, delay)
713            });
714            let scope = timing_scope!("operation");
715            let result = runtime.block_on(func(admission));
716            scope.finish();
717            result
718        };
719        match &res {
720            Ok(summary) => {
721                if print_summary || verbose > 0 {
722                    println!("{summary}");
723                }
724            }
725            Err(err) => {
726                if !quiet {
727                    println!("{err:?}");
728                }
729            }
730        }
731        if (print_summary || verbose > 0)
732            && !suppress_runtime_stats
733            && let Err(err) = runtime_setup::print_runtime_stats()
734        {
735            println!("Failed to print runtime stats: {err:?}");
736        }
737        // Signal the histogram logger to exit cleanly so its final
738        // snapshot is written before the runtime drops and aborts it.
739        // No-op when histograms are disabled.
740        signal_logger_cancel();
741        if let Some(handle) = take_logger_handle() {
742            // Bound the wait so a stuck logger can't hang shutdown — 1s is
743            // generous: the logger only does a snapshot+flush on cancel.
744            let _ = runtime.block_on(async {
745                tokio::time::timeout(std::time::Duration::from_secs(1), handle).await
746            });
747        }
748        // Bounded shutdown instead of a plain drop, which WAITS for every running blocking-pool
749        // closure. A blocking syscall parked on dead media (an NFS readdir that never returns, the
750        // stdin watchdog's read(2) that only unblocks when sshd notices) would otherwise keep the
751        // process alive indefinitely after the operation itself already failed and reported.
752        // Async tasks are still dropped normally — destructors (reused-directory ACL rollbacks
753        // included) run before the wait begins; only stuck blocking threads are abandoned to
754        // process exit once the deadline passes.
755        runtime.shutdown_timeout(std::time::Duration::from_secs(10));
756        res
757    };
758    // Clear process-wide state so a second `run()` in the same process
759    // starts on a clean slate. Without this, a later run inherits the
760    // previous auto-meta sample sink and ops-in-flight cap, and its
761    // probes acquire against stale limits even when auto_meta is off.
762    reset_process_throttle_state();
763    if let Err(error) = tracing_guards.finish() {
764        eprintln!("Failed to write scoped timings: {error:#}");
765        return None;
766    }
767    res.ok()
768}
769
770/// Reset process-wide throttle + congestion state to its pre-`run()`
771/// defaults. Called by [`run`] on exit so callers that invoke it more
772/// than once in a single process (library users, integration tests
773/// outside this crate) aren't affected by the previous invocation's
774/// decisions.
775fn reset_process_throttle_state() {
776    congestion::clear_sample_sink();
777    observability::clear();
778    for &side in &throttle::Side::ALL {
779        for &op in &throttle::MetadataOp::ALL {
780            throttle::set_max_ops_in_flight(throttle::Resource::meta(side, op), 0);
781        }
782    }
783    throttle::disable_ops_throttle();
784    // without these resets, a second run() in the same process inherits the previous run's
785    // file-admission caps and iops-throttle. `None` disables the admission semaphores, so the next
786    // run sees a clean slate and can either configure a fresh value or leave admission unlimited.
787    throttle::set_admission_limits(None);
788    throttle::init_iops_tokens(0);
789}