iperf3-rs 1.0.1

Rust API for libiperf with live iperf3 metrics export
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
//! High-level command API for running libiperf tests from Rust.
//!
//! `IperfCommand` deliberately accepts argv-style iperf arguments rather than a
//! typed Rust clone of every upstream option. This keeps compatibility anchored
//! to libiperf's own parser while still giving Rust callers structured results
//! and live metric streams.

use std::path::Path;
use std::sync::{Mutex, OnceLock};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use crossbeam_channel::{Sender, bounded};

use crate::iperf::{IperfTest, Role};
#[cfg(feature = "pushgateway")]
use crate::metrics::IntervalMetricsReporter;
use crate::metrics::{
    CallbackMetricsReporter, MetricEvent, MetricsMode, MetricsStream, metric_event_stream,
};
#[cfg(feature = "pushgateway")]
use crate::pushgateway::{PushGateway, PushGatewayConfig};
use crate::{Error, Result};

static RUN_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

/// Builder for running an iperf test through libiperf.
///
/// The typed helpers append ordinary iperf arguments such as `-c`, `-p`, and
/// `-t`. The lower-level [`IperfCommand::arg`] and [`IperfCommand::args`]
/// methods remain available for upstream options that do not have a dedicated
/// Rust helper.
///
/// Library runs suppress libiperf's normal stdout output by default. Use
/// [`IperfCommand::inherit_output`] for upstream-style terminal output or
/// [`IperfCommand::logfile`] to send that output to a file.
///
/// # Execution model
///
/// High-level runs are serialized inside the process because libiperf keeps
/// process-global state. [`RunningIperf`] is therefore a completion observer,
/// not a cancellation handle. Dropping it detaches the worker thread, and
/// [`RunningIperf::wait_timeout`] only stops waiting. It does not stop libiperf
/// or release this crate's process-wide run lock.
///
/// Use one-off server mode for library servers, or run long-lived and
/// externally cancellable iperf workloads in a helper process that the
/// embedding application can terminate.
///
/// # Examples
///
/// ```no_run
/// use std::time::Duration;
///
/// use iperf3_rs::{IperfCommand, Result};
///
/// fn main() -> Result<()> {
///     let mut command = IperfCommand::client("127.0.0.1");
///     command.duration(Duration::from_secs(5));
///
///     let result = command.run()?;
///     println!("{:?}", result.role());
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct IperfCommand {
    program: String,
    args: Vec<String>,
    metrics_mode: MetricsMode,
    #[cfg(feature = "pushgateway")]
    pushgateway: Option<PushGatewayRun>,
    allow_unbounded_server: bool,
    suppress_output: bool,
}

#[cfg(feature = "pushgateway")]
#[derive(Debug, Clone)]
struct PushGatewayRun {
    config: PushGatewayConfig,
    mode: MetricsMode,
}

impl IperfCommand {
    /// Create a command with no iperf role selected yet.
    pub fn new() -> Self {
        Self {
            program: "iperf3-rs".to_owned(),
            args: Vec::new(),
            metrics_mode: MetricsMode::Disabled,
            #[cfg(feature = "pushgateway")]
            pushgateway: None,
            allow_unbounded_server: false,
            suppress_output: true,
        }
    }

    /// Create a client command equivalent to `iperf3 -c HOST`.
    pub fn client(host: impl Into<String>) -> Self {
        let mut command = Self::new();
        command.arg("-c").arg(host);
        command
    }

    /// Create a one-off server command equivalent to `iperf3 -s -1`.
    ///
    /// This is the preferred server constructor for library code because the
    /// run exits after one accepted test and releases the process-wide libiperf
    /// lock.
    pub fn server_once() -> Self {
        let mut command = Self::new();
        command.args(["-s", "-1"]);
        command
    }

    /// Create a long-lived server command equivalent to `iperf3 -s`.
    ///
    /// Long-lived servers keep the high-level libiperf lock held until the
    /// server exits. The library does not provide in-process cancellation for
    /// an active libiperf server, and dropping [`RunningIperf`] detaches rather
    /// than stops it. Use this only for a process dedicated to serving tests or
    /// for a helper process that the parent application can terminate from the
    /// outside.
    pub fn server_unbounded() -> Self {
        let mut command = Self::new();
        command.arg("-s").allow_unbounded_server(true);
        command
    }

    /// Override the program name passed as `argv[0]` to libiperf.
    pub fn program(&mut self, program: impl Into<String>) -> &mut Self {
        self.program = program.into();
        self
    }

    /// Append one iperf argument.
    pub fn arg(&mut self, arg: impl Into<String>) -> &mut Self {
        self.args.push(arg.into());
        self
    }

    /// Append several iperf arguments.
    pub fn args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.args.extend(args.into_iter().map(Into::into));
        self
    }

    /// Set the server port with iperf's `-p` option.
    pub fn port(&mut self, port: u16) -> &mut Self {
        self.arg("-p").arg(port.to_string())
    }

    /// Set client test duration with iperf's `-t` option.
    ///
    /// Upstream iperf parses `-t` as whole seconds. Sub-second durations are
    /// rounded up so the typed API does not silently truncate a nonzero
    /// [`Duration`] to `0`.
    pub fn duration(&mut self, duration: Duration) -> &mut Self {
        self.arg("-t").arg(whole_seconds_arg(duration))
    }

    /// Set reporting interval with iperf's `-i` option.
    pub fn report_interval(&mut self, interval: Duration) -> &mut Self {
        self.arg("-i").arg(decimal_seconds_arg(interval))
    }

    /// Send iperf output to a log file with iperf's `--logfile` option.
    ///
    /// Explicit log files are honored even though high-level library runs are
    /// quiet by default.
    pub fn logfile(&mut self, path: impl AsRef<Path>) -> &mut Self {
        self.arg("--logfile")
            .arg(path.as_ref().to_string_lossy().into_owned())
    }

    /// Suppress libiperf's normal text or JSON writes to the process stdout.
    ///
    /// This is the default for `IperfCommand` so library use does not
    /// unexpectedly write to the embedding application's terminal. Retained
    /// JSON remains available through [`IperfResult::json_output`] when
    /// [`IperfCommand::json`] is enabled.
    pub fn quiet(&mut self) -> &mut Self {
        self.suppress_output = true;
        self
    }

    /// Let libiperf write normal output to this process' stdout.
    ///
    /// This matches upstream `iperf3` output behavior for applications that
    /// intentionally want human-readable output from library runs.
    pub fn inherit_output(&mut self) -> &mut Self {
        self.suppress_output = false;
        self
    }

    /// Set control connection setup timeout with iperf's `--connect-timeout`.
    ///
    /// Upstream iperf expects milliseconds. Nonzero sub-millisecond durations
    /// are rounded up so intent is not lost.
    pub fn connect_timeout(&mut self, timeout: Duration) -> &mut Self {
        self.arg("--connect-timeout").arg(milliseconds_arg(timeout))
    }

    /// Omit pre-test statistics for the given duration with iperf's `-O`.
    pub fn omit(&mut self, duration: Duration) -> &mut Self {
        self.arg("-O").arg(decimal_seconds_arg(duration))
    }

    /// Bind to a local address or `address%device` with iperf's `-B`.
    pub fn bind(&mut self, address: impl Into<String>) -> &mut Self {
        self.arg("-B").arg(address)
    }

    /// Enable UDP mode with iperf's `-u` option.
    pub fn udp(&mut self) -> &mut Self {
        self.arg("-u")
    }

    /// Enable SCTP mode with iperf's `--sctp` option.
    ///
    /// This option is available only when the linked libiperf was built with
    /// SCTP support; otherwise libiperf reports the unsupported option.
    pub fn sctp(&mut self) -> &mut Self {
        self.arg("--sctp")
    }

    /// Set target bitrate in bits per second with iperf's `-b` option.
    pub fn bitrate_bits_per_second(&mut self, bits_per_second: u64) -> &mut Self {
        self.arg("-b").arg(bits_per_second.to_string())
    }

    /// Set the number of parallel client streams with iperf's `-P` option.
    pub fn parallel_streams(&mut self, streams: u16) -> &mut Self {
        self.arg("-P").arg(streams.to_string())
    }

    /// Enable reverse mode with iperf's `-R` option.
    pub fn reverse(&mut self) -> &mut Self {
        self.arg("-R")
    }

    /// Enable bidirectional mode with iperf's `--bidir` option.
    pub fn bidirectional(&mut self) -> &mut Self {
        self.arg("--bidir")
    }

    /// Disable Nagle's algorithm with iperf's `-N` option.
    pub fn no_delay(&mut self) -> &mut Self {
        self.arg("-N")
    }

    /// Use zero-copy send with iperf's `-Z` option.
    pub fn zerocopy(&mut self) -> &mut Self {
        self.arg("-Z")
    }

    /// Set TCP congestion control algorithm with iperf's `-C` option.
    ///
    /// Upstream support depends on the operating system and linked libiperf
    /// build; unsupported values are reported by libiperf when the command
    /// parses or runs.
    pub fn congestion_control(&mut self, algorithm: impl Into<String>) -> &mut Self {
        self.arg("-C").arg(algorithm)
    }

    /// Request retained JSON output with iperf's `-J` option.
    pub fn json(&mut self) -> &mut Self {
        self.arg("-J")
    }

    /// Enable or disable callback metrics for this run.
    ///
    /// [`MetricsMode::Interval`] and [`MetricsMode::Window`] preserve every
    /// emitted event. Callers that spawn a metrics stream must keep draining it
    /// for the lifetime of the run. Blocking [`IperfCommand::run`] collects all
    /// emitted events in memory before returning, so it is intended for bounded
    /// client runs or one-off servers rather than long-lived servers.
    pub fn metrics(&mut self, mode: MetricsMode) -> &mut Self {
        self.metrics_mode = mode;
        self
    }

    /// Push live metrics for this run directly to a Pushgateway.
    ///
    /// `MetricsMode::Interval` uses the same freshness-oriented queue as the
    /// CLI's immediate push mode. `MetricsMode::Window(duration)` uses the same
    /// aggregation behavior as `--push.interval`. `MetricsMode::Disabled` is
    /// rejected when the command is started.
    ///
    /// Direct Pushgateway delivery and [`IperfCommand::spawn_with_metrics`] are
    /// currently mutually exclusive for one run because libiperf exposes a
    /// single reporter callback. Use [`IperfCommand::spawn_with_metrics`] plus
    /// [`PushGateway::push`] or [`PushGateway::push_window`] when application
    /// code needs both live inspection and custom push behavior.
    ///
    /// Delivery is best-effort: Pushgateway push/delete failures are logged to
    /// stderr and do not make the iperf run fail. Applications that require
    /// strict delivery should use [`IperfCommand::spawn_with_metrics`] and call
    /// [`PushGateway::push`] or [`PushGateway::push_window`] themselves.
    #[cfg(feature = "pushgateway")]
    pub fn pushgateway(&mut self, config: PushGatewayConfig, mode: MetricsMode) -> &mut Self {
        self.pushgateway = Some(PushGatewayRun { config, mode });
        self
    }

    /// Disable direct Pushgateway delivery for this command.
    #[cfg(feature = "pushgateway")]
    pub fn clear_pushgateway(&mut self) -> &mut Self {
        self.pushgateway = None;
        self
    }

    /// Run the iperf test to completion while pushing metrics to Pushgateway.
    ///
    /// Pushgateway delivery uses the same best-effort policy as the CLI. This
    /// method returns an error for setup or libiperf execution failures, but
    /// transient push/delete failures are logged and do not change the result.
    /// Use [`IperfCommand::spawn_with_metrics`] plus [`PushGateway::push`] or
    /// [`PushGateway::push_window`] when delivery failures must be handled
    /// strictly by application code.
    #[cfg(feature = "pushgateway")]
    pub fn run_with_pushgateway(
        &self,
        config: PushGatewayConfig,
        mode: MetricsMode,
    ) -> Result<IperfResult> {
        let mut command = self.clone();
        command.pushgateway = Some(PushGatewayRun { config, mode });
        command.run()
    }

    /// Run iperf on a worker thread while pushing metrics to Pushgateway.
    ///
    /// Pushgateway delivery is best-effort for this convenience method; use
    /// [`IperfCommand::spawn_with_metrics`] and call [`PushGateway`] directly
    /// when the application must treat delivery errors as run failures.
    #[cfg(feature = "pushgateway")]
    pub fn spawn_with_pushgateway(
        &self,
        config: PushGatewayConfig,
        mode: MetricsMode,
    ) -> Result<RunningIperf> {
        let mut command = self.clone();
        command.pushgateway = Some(PushGatewayRun { config, mode });
        command.spawn()
    }

    /// Allow `-s` server runs that do not include iperf's one-off option.
    ///
    /// Long-lived servers keep libiperf running on the worker thread and keep
    /// this crate's process-wide libiperf lock held. The default is therefore
    /// conservative: server mode must use `-1`/`--one-off` unless this opt-in is
    /// set. The CLI does not use this high-level API, so normal `iperf3-rs -s`
    /// behavior is unchanged. Once started, an unbounded in-process server must
    /// exit through libiperf itself; this API intentionally does not expose an
    /// in-process cancellation primitive. Prefer a dedicated helper process
    /// whenever the owner must enforce an external timeout or stop policy.
    pub fn allow_unbounded_server(&mut self, allow: bool) -> &mut Self {
        self.allow_unbounded_server = allow;
        self
    }

    /// Run the iperf test to completion and collect metric events in memory.
    ///
    /// When metrics are enabled, every emitted event is retained in the returned
    /// [`IperfResult`]. Keep metrics disabled for long-running or unbounded
    /// runs, or use [`IperfCommand::spawn_with_metrics`] and drain the stream
    /// while the run is active.
    pub fn run(&self) -> Result<IperfResult> {
        run_command(self.clone(), None)
    }

    /// Run iperf on a worker thread and optionally stream metric events live.
    ///
    /// If metrics are enabled, call [`RunningIperf::take_metrics`] before
    /// [`RunningIperf::wait`] to consume live events. Dropping the returned
    /// handle detaches the worker and does not cancel the underlying libiperf
    /// run. If you keep the metrics stream, drain it continuously for the
    /// lifetime of the run; every-sample streams use unbounded queues so the
    /// libiperf reporting callback never blocks on application code.
    pub fn spawn(&self) -> Result<RunningIperf> {
        let command = self.clone();
        let (ready_tx, ready_rx) = bounded::<ReadyMessage>(1);
        let handle = thread::spawn(move || run_command(command, Some(ready_tx)));

        match ready_rx.recv() {
            Ok(Ok(metrics)) => Ok(RunningIperf {
                handle: Some(handle),
                metrics,
            }),
            Ok(Err(err)) => {
                let _ = handle.join();
                Err(Error::worker(err))
            }
            Err(err) => {
                let _ = handle.join();
                Err(Error::worker(format!(
                    "iperf worker exited before setup completed: {err}"
                )))
            }
        }
    }

    /// Run iperf on a worker thread and return the live metric stream.
    ///
    /// This is a convenience wrapper around [`IperfCommand::metrics`],
    /// [`IperfCommand::spawn`], and [`RunningIperf::take_metrics`] for callers
    /// that know they want metrics for this run. The returned stream is part of
    /// the run contract: drain it until it closes, or drop it if metrics are no
    /// longer needed. Keeping it alive but unread can grow memory on long runs.
    pub fn spawn_with_metrics(&self, mode: MetricsMode) -> Result<(RunningIperf, MetricsStream)> {
        let mut command = self.clone();
        command.metrics(mode);
        let mut running = command.spawn()?;
        let metrics = running
            .take_metrics()
            .ok_or_else(|| Error::internal("metrics stream was not created"))?;
        Ok((running, metrics))
    }

    fn argv(&self) -> Vec<String> {
        let mut argv = Vec::with_capacity(self.args.len() + 1);
        argv.push(self.program.clone());
        argv.extend(self.args.iter().cloned());
        argv
    }

    fn should_suppress_output(&self) -> bool {
        self.suppress_output && !self.has_logfile_arg()
    }

    fn has_logfile_arg(&self) -> bool {
        self.args
            .iter()
            .any(|arg| arg == "--logfile" || arg.starts_with("--logfile="))
    }
}

impl Default for IperfCommand {
    fn default() -> Self {
        Self::new()
    }
}

/// Completed result from a blocking or spawned iperf run.
#[derive(Debug)]
pub struct IperfResult {
    role: Role,
    json_output: Option<String>,
    metrics: Vec<MetricEvent>,
}

impl IperfResult {
    /// Role selected by libiperf after parsing the supplied arguments.
    pub fn role(&self) -> Role {
        self.role
    }

    /// Upstream JSON result if JSON output was requested and libiperf retained it.
    pub fn json_output(&self) -> Option<&str> {
        self.json_output.as_deref()
    }

    /// Parse the retained upstream JSON result as a [`serde_json::Value`].
    ///
    /// Returns `None` when JSON output was not requested with
    /// [`IperfCommand::json`]. The raw string remains available through
    /// [`IperfResult::json_output`] for callers that prefer their own parser.
    #[cfg(feature = "serde")]
    pub fn json_value(&self) -> Option<std::result::Result<serde_json::Value, serde_json::Error>> {
        self.json_output.as_deref().map(serde_json::from_str)
    }

    /// Metric events collected by `IperfCommand::run`.
    ///
    /// Spawned commands deliver live metrics through `RunningIperf` instead, so
    /// their completed result does not duplicate the stream contents.
    pub fn metrics(&self) -> &[MetricEvent] {
        &self.metrics
    }
}

/// Handle for an iperf run executing on a worker thread.
///
/// This handle observes completion; it does not own a safe cancellation
/// mechanism for the underlying libiperf run. Dropping it detaches the worker.
/// `try_wait`, `wait_timeout`, and `wait` only observe or join the worker; none
/// of them requests libiperf shutdown. Use one-off server mode or a dedicated
/// helper process when a run must be externally stopped, isolated from hangs, or
/// allowed to coexist with other runs in the parent process.
#[derive(Debug)]
#[must_use = "dropping RunningIperf detaches the worker; call wait to observe the iperf result"]
pub struct RunningIperf {
    handle: Option<JoinHandle<Result<IperfResult>>>,
    metrics: Option<MetricsStream>,
}

impl RunningIperf {
    /// Borrow the live metric stream, if metrics were enabled.
    pub fn metrics(&self) -> Option<&MetricsStream> {
        self.metrics.as_ref()
    }

    /// Take ownership of the live metric stream.
    pub fn take_metrics(&mut self) -> Option<MetricsStream> {
        self.metrics.take()
    }

    /// Return `true` if the worker thread has finished.
    pub fn is_finished(&self) -> bool {
        self.handle
            .as_ref()
            .map(JoinHandle::is_finished)
            .unwrap_or(true)
    }

    /// Return the result if the worker has finished, without blocking.
    ///
    /// After this returns `Ok(Some(_))`, the worker result has been consumed and
    /// later calls to `try_wait`, `wait_timeout`, or `wait` will report that the
    /// run was already observed.
    pub fn try_wait(&mut self) -> Result<Option<IperfResult>> {
        if !self.is_finished() {
            return Ok(None);
        }
        self.take_finished_result().map(Some)
    }

    /// Wait up to `timeout` for the worker to finish.
    ///
    /// Returns `Ok(None)` when the timeout expires before the iperf run exits.
    /// A zero timeout performs a single nonblocking poll. Timeout expiration
    /// does not stop the iperf run; call this again, call [`RunningIperf::wait`],
    /// or manage cancellation outside this in-process API.
    pub fn wait_timeout(&mut self, timeout: Duration) -> Result<Option<IperfResult>> {
        let deadline = Instant::now()
            .checked_add(timeout)
            .unwrap_or_else(Instant::now);
        loop {
            if self.is_finished() {
                return self.take_finished_result().map(Some);
            }
            if timeout.is_zero() || Instant::now() >= deadline {
                return Ok(None);
            }
            thread::sleep(
                Duration::from_millis(10).min(deadline.saturating_duration_since(Instant::now())),
            );
        }
    }

    /// Wait until the iperf worker exits.
    pub fn wait(mut self) -> Result<IperfResult> {
        self.take_handle()?
            .join()
            .map_err(|_| Error::worker("iperf worker thread panicked"))?
    }

    fn take_finished_result(&mut self) -> Result<IperfResult> {
        self.take_handle()?
            .join()
            .map_err(|_| Error::worker("iperf worker thread panicked"))?
    }

    fn take_handle(&mut self) -> Result<JoinHandle<Result<IperfResult>>> {
        self.handle
            .take()
            .ok_or_else(|| Error::worker("iperf worker result was already observed"))
    }
}

type ReadyMessage = std::result::Result<Option<MetricsStream>, String>;

struct RunSetup {
    test: IperfTest,
    role: Role,
    callback: Option<CallbackMetricsReporter>,
    stream: Option<MetricsStream>,
    worker: Option<JoinHandle<()>>,
    #[cfg(feature = "pushgateway")]
    push_reporter: Option<IntervalMetricsReporter>,
}

fn run_command(command: IperfCommand, ready: Option<Sender<ReadyMessage>>) -> Result<IperfResult> {
    let _guard = run_lock()
        .lock()
        .map_err(|_| Error::internal("libiperf run lock is poisoned"))?;

    let mut setup = match setup_run(command) {
        Ok(setup) => setup,
        Err(err) => {
            notify_ready(ready, Err(format!("{err:#}")));
            return Err(err);
        }
    };

    let ready_stream = if ready.is_some() {
        setup.stream.take()
    } else {
        None
    };
    notify_ready(ready, Ok(ready_stream));

    let result = setup.test.run();
    let json_output = setup.test.json_output();

    // Removing the callback first closes the raw metrics channel, allowing the
    // event worker to flush any final window and exit before the result returns.
    drop(setup.callback.take());
    if let Some(worker) = setup.worker.take() {
        let _ = worker.join();
    }
    #[cfg(feature = "pushgateway")]
    let push_result = setup
        .push_reporter
        .take()
        .map(IntervalMetricsReporter::finish)
        .transpose();

    let metrics = setup
        .stream
        .map(|stream| stream.collect())
        .unwrap_or_default();

    result?;
    #[cfg(feature = "pushgateway")]
    push_result?;
    Ok(IperfResult {
        role: setup.role,
        json_output,
        metrics,
    })
}

fn setup_run(command: IperfCommand) -> Result<RunSetup> {
    validate_metrics_mode(command.metrics_mode)?;
    #[cfg(feature = "pushgateway")]
    validate_pushgateway_request(&command)?;

    let mut test = IperfTest::new()?;
    test.parse_arguments(&command.argv())?;
    if command.should_suppress_output() {
        test.suppress_output()?;
    }
    let role = test.role();
    validate_server_lifecycle(&command, &test, role)?;

    #[cfg(feature = "pushgateway")]
    let (callback, stream, worker, push_reporter) =
        if let Some(queue) = command.metrics_mode.callback_queue() {
            let (callback, rx) = CallbackMetricsReporter::attach(&mut test, queue)?;
            let (stream, worker) = metric_event_stream(rx, command.metrics_mode);
            (Some(callback), Some(stream), Some(worker), None)
        } else if let Some(pushgateway) = command.pushgateway {
            let sink = PushGateway::new(pushgateway.config)?;
            let reporter =
                IntervalMetricsReporter::attach(&mut test, sink, pushgateway.mode.push_interval())?;
            (None, None, None, Some(reporter))
        } else {
            (None, None, None, None)
        };
    #[cfg(not(feature = "pushgateway"))]
    let (callback, stream, worker) = match command.metrics_mode.callback_queue() {
        Some(queue) => {
            let (callback, rx) = CallbackMetricsReporter::attach(&mut test, queue)?;
            let (stream, worker) = metric_event_stream(rx, command.metrics_mode);
            (Some(callback), Some(stream), Some(worker))
        }
        None => (None, None, None),
    };

    Ok(RunSetup {
        test,
        role,
        callback,
        stream,
        worker,
        #[cfg(feature = "pushgateway")]
        push_reporter,
    })
}

fn notify_ready(ready: Option<Sender<ReadyMessage>>, message: ReadyMessage) {
    if let Some(ready) = ready {
        let _ = ready.send(message);
    }
}

fn run_lock() -> &'static Mutex<()> {
    // libiperf still has process-global state, including its current error and
    // signal/output hooks. The first public API keeps high-level runs
    // serialized so callers do not accidentally depend on best-effort
    // in-process parallelism that libiperf does not clearly promise.
    //
    // If parallel library runs become important, prefer adding a process-backed
    // runner first. A helper process gives each libiperf instance its own
    // globals, lets the parent enforce real kill/timeout policy, and avoids
    // wedging later in-process runs behind a detached or hung worker. Removing
    // this lock for true in-process concurrency should come only after upstream
    // and shim state are audited and covered by stress tests.
    RUN_LOCK.get_or_init(|| Mutex::new(()))
}

fn validate_metrics_mode(mode: MetricsMode) -> Result<()> {
    if metrics_mode_is_valid(mode) {
        Ok(())
    } else {
        Err(Error::invalid_metrics_mode(
            "metrics window interval must be greater than zero",
        ))
    }
}

#[cfg(feature = "pushgateway")]
fn validate_pushgateway_request(command: &IperfCommand) -> Result<()> {
    let Some(pushgateway) = &command.pushgateway else {
        return Ok(());
    };
    if command.metrics_mode.is_enabled() {
        return Err(Error::invalid_argument(
            "direct Pushgateway delivery cannot be combined with a MetricsStream in the same IperfCommand run",
        ));
    }
    validate_pushgateway_mode(pushgateway.mode)
}

#[cfg(feature = "pushgateway")]
fn validate_pushgateway_mode(mode: MetricsMode) -> Result<()> {
    match mode {
        MetricsMode::Disabled => Err(Error::invalid_metrics_mode(
            "Pushgateway metrics mode must be Interval or Window",
        )),
        MetricsMode::Interval => Ok(()),
        MetricsMode::Window(interval) if interval.is_zero() => Err(Error::invalid_metrics_mode(
            "metrics window interval must be greater than zero",
        )),
        MetricsMode::Window(_) => Ok(()),
    }
}

#[cfg(feature = "pushgateway")]
impl MetricsMode {
    fn push_interval(self) -> Option<Duration> {
        match self {
            MetricsMode::Disabled | MetricsMode::Interval => None,
            MetricsMode::Window(interval) => Some(interval),
        }
    }
}

fn metrics_mode_is_valid(mode: MetricsMode) -> bool {
    !matches!(mode, MetricsMode::Window(interval) if interval.is_zero())
}

fn whole_seconds_arg(duration: Duration) -> String {
    let seconds = if duration.subsec_nanos() == 0 {
        duration.as_secs()
    } else {
        duration.as_secs().saturating_add(1)
    };
    seconds.to_string()
}

fn decimal_seconds_arg(duration: Duration) -> String {
    let seconds = duration.as_secs();
    let nanos = duration.subsec_nanos();
    if nanos == 0 {
        return seconds.to_string();
    }

    let mut value = format!("{seconds}.{nanos:09}");
    while value.ends_with('0') {
        value.pop();
    }
    value
}

fn milliseconds_arg(duration: Duration) -> String {
    let millis = duration.as_millis();
    let has_fractional_millis = !duration.subsec_nanos().is_multiple_of(1_000_000);
    if has_fractional_millis {
        millis.saturating_add(1).to_string()
    } else {
        millis.to_string()
    }
}

fn validate_server_lifecycle(command: &IperfCommand, test: &IperfTest, role: Role) -> Result<()> {
    if role == Role::Server && !test.one_off() && !command.allow_unbounded_server {
        return Err(Error::invalid_argument(
            "IperfCommand server mode must use -1/--one-off or opt in with allow_unbounded_server(true)",
        ));
    }
    Ok(())
}

#[cfg(kani)]
mod verification {
    use std::time::Duration;

    use super::*;

    #[kani::proof]
    fn zero_window_interval_is_the_only_invalid_metrics_mode() {
        let seconds: u8 = kani::any();
        let mode = MetricsMode::Window(Duration::from_secs(u64::from(seconds)));

        assert_eq!(metrics_mode_is_valid(mode), seconds != 0);
        assert!(metrics_mode_is_valid(MetricsMode::Disabled));
        assert!(metrics_mode_is_valid(MetricsMode::Interval));
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use crate::ErrorKind;
    #[cfg(feature = "pushgateway")]
    use url::Url;

    use super::*;

    #[test]
    fn argv_includes_program_name_before_iperf_arguments() {
        let mut command = IperfCommand::new();
        command.arg("-c").arg("127.0.0.1");

        assert_eq!(
            command.argv(),
            vec![
                "iperf3-rs".to_owned(),
                "-c".to_owned(),
                "127.0.0.1".to_owned()
            ]
        );
    }

    #[test]
    fn custom_program_name_is_used_as_argv_zero() {
        let mut command = IperfCommand::new();
        command.program("iperf3").arg("-v");

        assert_eq!(command.argv(), vec!["iperf3".to_owned(), "-v".to_owned()]);
    }

    #[test]
    fn library_output_is_quiet_by_default() {
        let command = IperfCommand::new();

        assert!(command.should_suppress_output());
    }

    #[test]
    fn inherit_output_disables_library_quiet_default() {
        let mut command = IperfCommand::new();
        command.inherit_output();

        assert!(!command.should_suppress_output());

        command.quiet();
        assert!(command.should_suppress_output());
    }

    #[test]
    fn explicit_logfile_disables_null_output_sink() {
        let mut typed = IperfCommand::new();
        typed.logfile("iperf.log");

        let mut raw_split = IperfCommand::new();
        raw_split.arg("--logfile").arg("iperf.log");

        let mut raw_equals = IperfCommand::new();
        raw_equals.arg("--logfile=iperf.log");

        assert!(!typed.should_suppress_output());
        assert!(!raw_split.should_suppress_output());
        assert!(!raw_equals.should_suppress_output());
    }

    #[test]
    fn typed_client_builder_appends_iperf_arguments() {
        let mut command = IperfCommand::client("192.0.2.10");
        command
            .port(5202)
            .duration(Duration::from_secs(3))
            .report_interval(Duration::from_millis(500))
            .udp()
            .bitrate_bits_per_second(1_000_000)
            .parallel_streams(4)
            .reverse()
            .json()
            .arg("--get-server-output");

        assert_eq!(
            command.argv(),
            vec![
                "iperf3-rs".to_owned(),
                "-c".to_owned(),
                "192.0.2.10".to_owned(),
                "-p".to_owned(),
                "5202".to_owned(),
                "-t".to_owned(),
                "3".to_owned(),
                "-i".to_owned(),
                "0.5".to_owned(),
                "-u".to_owned(),
                "-b".to_owned(),
                "1000000".to_owned(),
                "-P".to_owned(),
                "4".to_owned(),
                "-R".to_owned(),
                "-J".to_owned(),
                "--get-server-output".to_owned(),
            ]
        );
    }

    #[test]
    fn typed_operational_helpers_append_iperf_arguments() {
        let mut command = IperfCommand::client("192.0.2.10");
        command
            .logfile("iperf.log")
            .connect_timeout(Duration::from_millis(1500))
            .omit(Duration::from_millis(250))
            .bind("127.0.0.1%lo0")
            .no_delay()
            .zerocopy()
            .congestion_control("cubic");

        assert_eq!(
            command.argv(),
            vec![
                "iperf3-rs".to_owned(),
                "-c".to_owned(),
                "192.0.2.10".to_owned(),
                "--logfile".to_owned(),
                "iperf.log".to_owned(),
                "--connect-timeout".to_owned(),
                "1500".to_owned(),
                "-O".to_owned(),
                "0.25".to_owned(),
                "-B".to_owned(),
                "127.0.0.1%lo0".to_owned(),
                "-N".to_owned(),
                "-Z".to_owned(),
                "-C".to_owned(),
                "cubic".to_owned(),
            ]
        );
    }

    #[test]
    fn typed_server_constructors_select_expected_lifecycle() {
        let one_off = IperfCommand::server_once();
        assert_eq!(
            one_off.argv(),
            vec!["iperf3-rs".to_owned(), "-s".to_owned(), "-1".to_owned()]
        );
        assert!(!one_off.allow_unbounded_server);

        let unbounded = IperfCommand::server_unbounded();
        assert_eq!(
            unbounded.argv(),
            vec!["iperf3-rs".to_owned(), "-s".to_owned()]
        );
        assert!(unbounded.allow_unbounded_server);
    }

    #[test]
    fn bidirectional_helper_appends_long_option() {
        let mut command = IperfCommand::client("192.0.2.10");
        command.bidirectional();

        assert_eq!(
            command.argv(),
            vec![
                "iperf3-rs".to_owned(),
                "-c".to_owned(),
                "192.0.2.10".to_owned(),
                "--bidir".to_owned()
            ]
        );
    }

    #[test]
    fn sctp_helper_appends_long_option() {
        let mut command = IperfCommand::client("192.0.2.10");
        command.sctp();

        assert_eq!(
            command.argv(),
            vec![
                "iperf3-rs".to_owned(),
                "-c".to_owned(),
                "192.0.2.10".to_owned(),
                "--sctp".to_owned()
            ]
        );
    }

    #[cfg(feature = "pushgateway")]
    #[test]
    fn pushgateway_helper_records_delivery_config() {
        let config = PushGatewayConfig::new(Url::parse("http://localhost:9091").unwrap())
            .label("scenario", "library");
        let mut command = IperfCommand::client("192.0.2.10");
        command.pushgateway(config, MetricsMode::Window(Duration::from_secs(5)));

        let pushgateway = command.pushgateway.as_ref().unwrap();
        assert_eq!(
            pushgateway.mode,
            MetricsMode::Window(Duration::from_secs(5))
        );
        assert_eq!(
            pushgateway.config.labels,
            [("scenario".to_owned(), "library".to_owned())]
        );

        command.clear_pushgateway();
        assert!(command.pushgateway.is_none());
    }

    #[cfg(feature = "pushgateway")]
    #[test]
    fn pushgateway_convenience_helpers_do_not_persist_config() {
        let mut command = IperfCommand::new();
        command.metrics(MetricsMode::Window(Duration::ZERO));

        let result = command.run_with_pushgateway(
            PushGatewayConfig::new(Url::parse("http://localhost:9091").unwrap()),
            MetricsMode::Interval,
        );

        assert!(result.is_err());
        assert!(command.pushgateway.is_none());
    }

    #[test]
    fn spawn_with_metrics_does_not_persist_metrics_mode() {
        let command = IperfCommand::new();

        let err = command
            .spawn_with_metrics(MetricsMode::Window(Duration::ZERO))
            .unwrap_err();

        assert!(err.to_string().contains("greater than zero"), "{err:#}");
        assert_eq!(command.metrics_mode, MetricsMode::Disabled);
    }

    #[test]
    fn duration_helpers_preserve_nonzero_subsecond_intent() {
        assert_eq!(whole_seconds_arg(Duration::ZERO), "0");
        assert_eq!(whole_seconds_arg(Duration::from_millis(1)), "1");
        assert_eq!(whole_seconds_arg(Duration::from_millis(1500)), "2");
        assert_eq!(decimal_seconds_arg(Duration::ZERO), "0");
        assert_eq!(decimal_seconds_arg(Duration::from_millis(250)), "0.25");
        assert_eq!(decimal_seconds_arg(Duration::new(1, 1)), "1.000000001");
        assert_eq!(milliseconds_arg(Duration::ZERO), "0");
        assert_eq!(milliseconds_arg(Duration::from_nanos(1)), "1");
        assert_eq!(milliseconds_arg(Duration::from_millis(1500)), "1500");
        assert_eq!(milliseconds_arg(Duration::new(1, 1)), "1001");
    }

    #[test]
    fn unbounded_server_mode_is_rejected_by_default() {
        let command = {
            let mut command = IperfCommand::new();
            command.arg("-s");
            command
        };

        let err = match setup_run(command) {
            Ok(_) => panic!("unbounded server should be rejected"),
            Err(err) => err,
        };
        assert_eq!(err.kind(), ErrorKind::InvalidArgument);
        assert!(err.to_string().contains("allow_unbounded_server"));
    }

    #[test]
    fn one_off_server_mode_is_allowed() {
        let command = {
            let mut command = IperfCommand::new();
            command.args(["-s", "-1"]);
            command
        };

        let setup = setup_run(command).unwrap();
        assert_eq!(setup.role, Role::Server);
    }

    #[test]
    fn unbounded_server_mode_can_be_explicitly_allowed() {
        let command = {
            let mut command = IperfCommand::new();
            command.arg("-s").allow_unbounded_server(true);
            command
        };

        let setup = setup_run(command).unwrap();
        assert_eq!(setup.role, Role::Server);
    }

    #[test]
    fn zero_metrics_window_interval_is_rejected_before_running_iperf() {
        let mut command = IperfCommand::new();
        command.metrics(MetricsMode::Window(Duration::ZERO));

        let err = command.run().unwrap_err();
        assert_eq!(err.kind(), ErrorKind::InvalidMetricsMode);
        assert!(err.to_string().contains("greater than zero"));
    }

    #[cfg(feature = "pushgateway")]
    #[test]
    fn direct_pushgateway_rejects_disabled_or_zero_window_mode() {
        for mode in [MetricsMode::Disabled, MetricsMode::Window(Duration::ZERO)] {
            let command = {
                let mut command = IperfCommand::new();
                command.arg("-s").arg("-1").pushgateway(
                    PushGatewayConfig::new(Url::parse("http://localhost:9091").unwrap()),
                    mode,
                );
                command
            };

            let err = match setup_run(command) {
                Ok(_) => panic!("invalid Pushgateway mode should be rejected"),
                Err(err) => err,
            };
            assert_eq!(err.kind(), ErrorKind::InvalidMetricsMode);
        }
    }

    #[cfg(feature = "pushgateway")]
    #[test]
    fn direct_pushgateway_is_rejected_when_metrics_stream_is_enabled() {
        let command = {
            let mut command = IperfCommand::new();
            command
                .arg("-s")
                .arg("-1")
                .metrics(MetricsMode::Interval)
                .pushgateway(
                    PushGatewayConfig::new(Url::parse("http://localhost:9091").unwrap()),
                    MetricsMode::Interval,
                );
            command
        };

        let err = match setup_run(command) {
            Ok(_) => panic!("direct Pushgateway and MetricsStream should be rejected together"),
            Err(err) => err,
        };
        assert_eq!(err.kind(), ErrorKind::InvalidArgument);
        assert!(err.to_string().contains("cannot be combined"));
    }

    #[test]
    fn running_iperf_try_wait_observes_finished_worker_once() {
        let mut running = RunningIperf {
            handle: Some(thread::spawn(|| Ok(test_result()))),
            metrics: None,
        };

        let result = running
            .wait_timeout(Duration::from_secs(1))
            .unwrap()
            .expect("worker should finish");
        assert_eq!(result.role(), Role::Client);
        assert_eq!(running.try_wait().unwrap_err().kind(), ErrorKind::Worker);
    }

    #[test]
    fn running_iperf_try_wait_returns_none_while_worker_is_running() {
        let (release_tx, release_rx) = bounded::<()>(1);
        let mut running = RunningIperf {
            handle: Some(thread::spawn(move || {
                release_rx.recv().unwrap();
                Ok(test_result())
            })),
            metrics: None,
        };

        assert!(!running.is_finished());
        assert!(running.try_wait().unwrap().is_none());
        assert!(running.wait_timeout(Duration::ZERO).unwrap().is_none());

        release_tx.send(()).unwrap();
        assert!(
            running
                .wait_timeout(Duration::from_secs(1))
                .unwrap()
                .is_some()
        );
    }

    #[test]
    fn run_without_client_or_server_role_fails_fast() {
        let command = IperfCommand::new();

        let err = command.run().unwrap_err();
        assert_eq!(err.kind(), ErrorKind::Libiperf);
        assert!(
            err.to_string().contains("client (-c) or server (-s)"),
            "{err:#}"
        );
    }

    fn test_result() -> IperfResult {
        IperfResult {
            role: Role::Client,
            json_output: None,
            metrics: Vec::new(),
        }
    }
}