tokio-process-tools 0.8.0

Interact with processes spawned by tokio.
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
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
use crate::error::{SpawnError, TerminationError, WaitError};
use crate::output::{Output, RawOutput};
use crate::output_stream::broadcast::BroadcastOutputStream;
use crate::output_stream::single_subscriber::SingleSubscriberOutputStream;
use crate::output_stream::{BackpressureControl, FromStreamOptions};
use crate::panic_on_drop::PanicOnDrop;
use crate::terminate_on_drop::TerminateOnDrop;
use crate::{LineParsingOptions, NumBytes, OutputStream, signal};
use std::borrow::Cow;
use std::fmt::Debug;
use std::io;
use std::process::{ExitStatus, Stdio};
use std::time::Duration;
use tokio::process::{Child, ChildStdin};

const STDOUT_STREAM_NAME: &str = "stdout";
const STDERR_STREAM_NAME: &str = "stderr";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SingleSubscriberStreamConfig {
    pub(crate) chunk_size: NumBytes,
    pub(crate) channel_capacity: usize,
    pub(crate) backpressure_control: BackpressureControl,
}

/// Maximum time to wait for process termination after sending SIGKILL.
///
/// This is a safety timeout since SIGKILL should terminate processes immediately,
/// but there are rare cases where even SIGKILL may not work.
const SIGKILL_WAIT_TIMEOUT: Duration = Duration::from_secs(3);

/// Represents the stdin stream of a child process.
///
/// stdin is always configured as piped, so it starts as `Open` with a [`ChildStdin`] handle
/// that can be used to write data to the process. It can be explicitly closed by calling
/// [`Stdin::close`], after which it transitions to the `Closed` state.
#[derive(Debug)]
pub enum Stdin {
    /// stdin is open and available for writing.
    Open(ChildStdin),
    /// stdin has been closed.
    Closed,
}

impl Stdin {
    /// Returns `true` if stdin is open and available for writing.
    #[must_use]
    pub fn is_open(&self) -> bool {
        matches!(self, Stdin::Open(_))
    }

    /// Returns a mutable reference to the underlying [`ChildStdin`] if open, or `None` if closed.
    pub fn as_mut(&mut self) -> Option<&mut ChildStdin> {
        match self {
            Stdin::Open(stdin) => Some(stdin),
            Stdin::Closed => None,
        }
    }

    /// Closes stdin by dropping the underlying [`ChildStdin`] handle.
    ///
    /// This sends `EOF` to the child process. After calling this method, this stdin
    /// will be in the `Closed` state and no further writes will be possible.
    pub fn close(&mut self) {
        *self = Stdin::Closed;
    }
}

/// Represents the running state of a process.
#[derive(Debug)]
pub enum RunningState {
    /// The process is still running.
    Running,

    /// The process has terminated with the given exit status.
    Terminated(ExitStatus),

    /// Failed to determine process state.
    Uncertain(io::Error),
}

impl RunningState {
    /// Returns `true` if the process is running, `false` otherwise.
    #[must_use]
    pub fn as_bool(&self) -> bool {
        match self {
            RunningState::Running => true,
            RunningState::Terminated(_) | RunningState::Uncertain(_) => false,
        }
    }
}

impl From<RunningState> for bool {
    fn from(is_running: RunningState) -> Self {
        match is_running {
            RunningState::Running => true,
            RunningState::Terminated(_) | RunningState::Uncertain(_) => false,
        }
    }
}

/// A handle to a spawned process with captured stdout/stderr streams.
///
/// This type provides methods for waiting on process completion, terminating the process,
/// and accessing its output streams. By default, processes must be explicitly waited on
/// or terminated before being dropped (see [`ProcessHandle::must_be_terminated`]).
///
/// If applicable, a process handle can be wrapped in a [`TerminateOnDrop`] to be terminated
/// automatically upon being dropped. Note that this requires a multi-threaded runtime!
#[derive(Debug)]
pub struct ProcessHandle<O: OutputStream> {
    pub(crate) name: Cow<'static, str>,
    child: Child,
    std_in: Stdin,
    std_out_stream: O,
    std_err_stream: O,
    cleanup_on_drop: bool,
    panic_on_drop: Option<PanicOnDrop>,
}

impl<O: OutputStream> Drop for ProcessHandle<O> {
    fn drop(&mut self) {
        if self.cleanup_on_drop {
            // We want users to explicitly await or terminate spawned processes.
            // If not done so, kill the process now to have some sort of last-resort cleanup.
            // A separate panic-on-drop guard may additionally raise a panic to signal the misuse.
            if let Err(err) = self.child.start_kill() {
                tracing::warn!(
                    process = %self.name,
                    error = %err,
                    "Failed to kill process while dropping an armed ProcessHandle"
                );
            }
        }
    }
}

impl ProcessHandle<BroadcastOutputStream> {
    /// Spawns a new process with broadcast output streams and custom channel capacities.
    ///
    /// This method is intended for internal use by the `Process` builder.
    /// Users should use `Process::new(cmd).spawn_broadcast()` instead.
    pub(crate) fn spawn_with_capacity(
        name: impl Into<Cow<'static, str>>,
        mut cmd: tokio::process::Command,
        stdout_chunk_size: NumBytes,
        stderr_chunk_size: NumBytes,
        stdout_channel_capacity: usize,
        stderr_channel_capacity: usize,
    ) -> Result<ProcessHandle<BroadcastOutputStream>, SpawnError> {
        stdout_chunk_size.assert_non_zero("stdout_chunk_size");
        stderr_chunk_size.assert_non_zero("stderr_chunk_size");

        let process_name = name.into();
        Self::prepare_command(&mut cmd)
            .spawn()
            .map(|child| {
                Self::new_from_child_with_piped_io_and_capacity(
                    process_name.clone(),
                    child,
                    stdout_chunk_size,
                    stderr_chunk_size,
                    stdout_channel_capacity,
                    stderr_channel_capacity,
                )
            })
            .map_err(|source| SpawnError::SpawnFailed {
                process_name,
                source,
            })
    }

    fn new_from_child_with_piped_io_and_capacity(
        name: impl Into<Cow<'static, str>>,
        mut child: Child,
        stdout_chunk_size: NumBytes,
        stderr_chunk_size: NumBytes,
        stdout_channel_capacity: usize,
        stderr_channel_capacity: usize,
    ) -> ProcessHandle<BroadcastOutputStream> {
        let std_in = match child.stdin.take() {
            Some(stdin) => Stdin::Open(stdin),
            None => Stdin::Closed,
        };
        let stdout = child
            .stdout
            .take()
            .expect("Child process stdout wasn't captured");
        let stderr = child
            .stderr
            .take()
            .expect("Child process stderr wasn't captured");

        let std_out_stream = BroadcastOutputStream::from_stream(
            stdout,
            STDOUT_STREAM_NAME,
            FromStreamOptions {
                chunk_size: stdout_chunk_size,
                channel_capacity: stdout_channel_capacity,
            },
        );
        let std_err_stream = BroadcastOutputStream::from_stream(
            stderr,
            STDERR_STREAM_NAME,
            FromStreamOptions {
                chunk_size: stderr_chunk_size,
                channel_capacity: stderr_channel_capacity,
            },
        );

        let mut this = ProcessHandle {
            name: name.into(),
            child,
            std_in,
            std_out_stream,
            std_err_stream,
            cleanup_on_drop: false,
            panic_on_drop: None,
        };
        this.must_be_terminated();
        this
    }

    /// Convenience function, waiting for the process to complete using
    /// [`ProcessHandle::wait_for_completion`] while collecting both `stdout` and `stderr`
    /// into individual `Vec<String>` collections using the provided [`LineParsingOptions`].
    ///
    /// You may want to destructure this using:
    /// ```no_run
    /// # use tokio::process::Command;
    /// # use tokio_process_tools::*;
    /// # tokio_test::block_on(async {
    /// # let mut proc = Process::new(Command::new("ls")).spawn_broadcast().unwrap();
    /// let Output {
    ///     status,
    ///     stdout,
    ///     stderr
    /// } = proc.wait_for_completion_with_output(None, LineParsingOptions::default()).await.unwrap();
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process or collecting output fails.
    pub async fn wait_for_completion_with_output(
        &mut self,
        timeout: Option<Duration>,
        options: LineParsingOptions,
    ) -> Result<Output, WaitError> {
        let out_collector = self.stdout().collect_lines_into_vec(options);
        let err_collector = self.stderr().collect_lines_into_vec(options);

        let status = self.wait_for_completion(timeout).await?;

        let stdout = out_collector.wait().await?;
        let stderr = err_collector.wait().await?;

        Ok(Output {
            status,
            stdout,
            stderr,
        })
    }

    /// Convenience function, waiting for the process to complete using
    /// [`ProcessHandle::wait_for_completion`] while collecting both `stdout` and `stderr`
    /// into raw byte vectors.
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process or collecting output fails.
    pub async fn wait_for_completion_with_raw_output(
        &mut self,
        timeout: Option<Duration>,
    ) -> Result<RawOutput, WaitError> {
        let out_collector = self.stdout().collect_chunks_into_vec();
        let err_collector = self.stderr().collect_chunks_into_vec();

        let status = self.wait_for_completion(timeout).await?;

        let stdout = out_collector.wait().await?;
        let stderr = err_collector.wait().await?;

        Ok(RawOutput {
            status,
            stdout,
            stderr,
        })
    }

    /// Convenience function, waiting for the process to complete using
    /// [`ProcessHandle::wait_for_completion_or_terminate`] while collecting both `stdout` and `stderr`
    /// into individual `Vec<String>` collections using the provided [`LineParsingOptions`].
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process, terminating it, or collecting output fails.
    pub async fn wait_for_completion_with_output_or_terminate(
        &mut self,
        wait_timeout: Duration,
        interrupt_timeout: Duration,
        terminate_timeout: Duration,
        options: LineParsingOptions,
    ) -> Result<Output, WaitError> {
        let out_collector = self.stdout().collect_lines_into_vec(options);
        let err_collector = self.stderr().collect_lines_into_vec(options);

        let status = self
            .wait_for_completion_or_terminate(wait_timeout, interrupt_timeout, terminate_timeout)
            .await?;

        let stdout = out_collector.wait().await?;
        let stderr = err_collector.wait().await?;

        Ok(Output {
            status,
            stdout,
            stderr,
        })
    }

    /// Convenience function, waiting for the process to complete using
    /// [`ProcessHandle::wait_for_completion_or_terminate`] while collecting both `stdout` and
    /// `stderr` into raw byte vectors.
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process, terminating it, or collecting output fails.
    pub async fn wait_for_completion_with_raw_output_or_terminate(
        &mut self,
        wait_timeout: Duration,
        interrupt_timeout: Duration,
        terminate_timeout: Duration,
    ) -> Result<RawOutput, WaitError> {
        let out_collector = self.stdout().collect_chunks_into_vec();
        let err_collector = self.stderr().collect_chunks_into_vec();

        let status = self
            .wait_for_completion_or_terminate(wait_timeout, interrupt_timeout, terminate_timeout)
            .await?;

        let stdout = out_collector.wait().await?;
        let stderr = err_collector.wait().await?;

        Ok(RawOutput {
            status,
            stdout,
            stderr,
        })
    }
}

impl ProcessHandle<SingleSubscriberOutputStream> {
    /// Spawns a new process with single subscriber output streams and custom channel capacities.
    ///
    /// This method is intended for internal use by the `Process` builder.
    /// Users should use `Process::new(cmd).spawn_single_subscriber()` instead.
    pub(crate) fn spawn_with_capacity(
        name: impl Into<Cow<'static, str>>,
        mut cmd: tokio::process::Command,
        stdout_config: SingleSubscriberStreamConfig,
        stderr_config: SingleSubscriberStreamConfig,
    ) -> Result<Self, SpawnError> {
        stdout_config
            .chunk_size
            .assert_non_zero("stdout_config.chunk_size");
        stderr_config
            .chunk_size
            .assert_non_zero("stderr_config.chunk_size");

        let process_name = name.into();
        Self::prepare_command(&mut cmd)
            .spawn()
            .map(|child| {
                Self::new_from_child_with_piped_io_and_capacity(
                    process_name.clone(),
                    child,
                    stdout_config,
                    stderr_config,
                )
            })
            .map_err(|source| SpawnError::SpawnFailed {
                process_name,
                source,
            })
    }

    fn new_from_child_with_piped_io_and_capacity(
        name: impl Into<Cow<'static, str>>,
        mut child: Child,
        stdout_config: SingleSubscriberStreamConfig,
        stderr_config: SingleSubscriberStreamConfig,
    ) -> Self {
        let std_in = match child.stdin.take() {
            Some(stdin) => Stdin::Open(stdin),
            None => Stdin::Closed,
        };
        let stdout = child
            .stdout
            .take()
            .expect("Child process stdout wasn't captured");
        let stderr = child
            .stderr
            .take()
            .expect("Child process stderr wasn't captured");

        let std_out_stream = SingleSubscriberOutputStream::from_stream(
            stdout,
            STDOUT_STREAM_NAME,
            stdout_config.backpressure_control,
            FromStreamOptions {
                chunk_size: stdout_config.chunk_size,
                channel_capacity: stdout_config.channel_capacity,
            },
        );
        let std_err_stream = SingleSubscriberOutputStream::from_stream(
            stderr,
            STDERR_STREAM_NAME,
            stderr_config.backpressure_control,
            FromStreamOptions {
                chunk_size: stderr_config.chunk_size,
                channel_capacity: stderr_config.channel_capacity,
            },
        );

        let mut this = ProcessHandle {
            name: name.into(),
            child,
            std_in,
            std_out_stream,
            std_err_stream,
            cleanup_on_drop: false,
            panic_on_drop: None,
        };
        this.must_be_terminated();
        this
    }

    /// Convenience function, waiting for the process to complete using
    /// [`ProcessHandle::wait_for_completion`] while collecting both `stdout` and `stderr`
    /// into individual `Vec<String>` collections using the provided [`LineParsingOptions`].
    ///
    /// You may want to destructure this using:
    /// ```no_run
    /// # use tokio_process_tools::*;
    /// # tokio_test::block_on(async {
    /// # let mut proc = Process::new(tokio::process::Command::new("ls")).spawn_broadcast().unwrap();
    /// let Output {
    ///     status,
    ///     stdout,
    ///     stderr
    /// } = proc.wait_for_completion_with_output(None, LineParsingOptions::default()).await.unwrap();
    /// # });
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process or collecting output fails.
    pub async fn wait_for_completion_with_output(
        &mut self,
        timeout: Option<Duration>,
        options: LineParsingOptions,
    ) -> Result<Output, WaitError> {
        let out_collector = self.stdout().collect_lines_into_vec(options);
        let err_collector = self.stderr().collect_lines_into_vec(options);

        let status = self.wait_for_completion(timeout).await?;

        let stdout = out_collector.wait().await?;
        let stderr = err_collector.wait().await?;

        Ok(Output {
            status,
            stdout,
            stderr,
        })
    }

    /// Convenience function, waiting for the process to complete using
    /// [`ProcessHandle::wait_for_completion`] while collecting both `stdout` and `stderr`
    /// into raw byte vectors.
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process or collecting output fails.
    pub async fn wait_for_completion_with_raw_output(
        &mut self,
        timeout: Option<Duration>,
    ) -> Result<RawOutput, WaitError> {
        let out_collector = self.stdout().collect_chunks_into_vec();
        let err_collector = self.stderr().collect_chunks_into_vec();

        let status = self.wait_for_completion(timeout).await?;

        let stdout = out_collector.wait().await?;
        let stderr = err_collector.wait().await?;

        Ok(RawOutput {
            status,
            stdout,
            stderr,
        })
    }

    /// Convenience function, waiting for the process to complete using
    /// [`ProcessHandle::wait_for_completion_or_terminate`] while collecting both `stdout` and `stderr`
    /// into individual `Vec<String>` collections using the provided [`LineParsingOptions`].
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process, terminating it, or collecting output fails.
    pub async fn wait_for_completion_with_output_or_terminate(
        &mut self,
        wait_timeout: Duration,
        interrupt_timeout: Duration,
        terminate_timeout: Duration,
        options: LineParsingOptions,
    ) -> Result<Output, WaitError> {
        let out_collector = self.stdout().collect_lines_into_vec(options);
        let err_collector = self.stderr().collect_lines_into_vec(options);

        let status = self
            .wait_for_completion_or_terminate(wait_timeout, interrupt_timeout, terminate_timeout)
            .await?;

        let stdout = out_collector.wait().await?;
        let stderr = err_collector.wait().await?;

        Ok(Output {
            status,
            stdout,
            stderr,
        })
    }

    /// Convenience function, waiting for the process to complete using
    /// [`ProcessHandle::wait_for_completion_or_terminate`] while collecting both `stdout` and
    /// `stderr` into raw byte vectors.
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process, terminating it, or collecting output fails.
    pub async fn wait_for_completion_with_raw_output_or_terminate(
        &mut self,
        wait_timeout: Duration,
        interrupt_timeout: Duration,
        terminate_timeout: Duration,
    ) -> Result<RawOutput, WaitError> {
        let out_collector = self.stdout().collect_chunks_into_vec();
        let err_collector = self.stderr().collect_chunks_into_vec();

        let status = self
            .wait_for_completion_or_terminate(wait_timeout, interrupt_timeout, terminate_timeout)
            .await?;

        let stdout = out_collector.wait().await?;
        let stderr = err_collector.wait().await?;

        Ok(RawOutput {
            status,
            stdout,
            stderr,
        })
    }
}

impl<O: OutputStream> ProcessHandle<O> {
    /// On Windows, you can only send `CTRL_C_EVENT` and `CTRL_BREAK_EVENT` to process groups,
    /// which works more like `killpg`. Sending to the current process ID will likely trigger
    /// undefined behavior of sending the event to every process that's attached to the console,
    /// i.e. sending the event to group ID 0. Therefore, we create a new process group
    /// for the child process we are about to spawn.
    ///
    /// See: <https://stackoverflow.com/questions/44124338/trying-to-implement-signal-ctrl-c-event-in-python3-6>
    fn prepare_platform_specifics(
        command: &mut tokio::process::Command,
    ) -> &mut tokio::process::Command {
        #[cfg(windows)]
        {
            use windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP;
            command.creation_flags(CREATE_NEW_PROCESS_GROUP)
        }
        #[cfg(not(windows))]
        {
            command
        }
    }

    fn prepare_command(command: &mut tokio::process::Command) -> &mut tokio::process::Command {
        Self::prepare_platform_specifics(command)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            // ProcessHandle itself performs the last-resort cleanup while its panic-on-drop guard
            // is armed. Keeping Tokio's unconditional kill-on-drop disabled ensures that
            // `must_not_be_terminated()` can really opt out.
            .kill_on_drop(false)
    }

    /// Returns the OS process ID if the process hasn't exited yet.
    ///
    /// Once this process has been polled to completion this will return None.
    pub fn id(&self) -> Option<u32> {
        self.child.id()
    }

    fn try_reap_exit_status(&mut self) -> Result<Option<ExitStatus>, io::Error> {
        match self.child.try_wait() {
            Ok(Some(exit_status)) => {
                self.must_not_be_terminated();
                Ok(Some(exit_status))
            }
            Ok(None) => Ok(None),
            Err(err) => Err(err),
        }
    }

    fn signalling_failed_or_reap(
        &mut self,
        signal: &'static str,
        source: io::Error,
    ) -> Result<ExitStatus, TerminationError> {
        match self.try_reap_exit_status() {
            Ok(Some(exit_status)) => Ok(exit_status),
            Ok(None) | Err(_) => Err(TerminationError::SignallingFailed {
                process_name: self.name.clone(),
                source,
                signal,
            }),
        }
    }

    /// Checks if the process is currently running.
    ///
    /// Returns [`RunningState::Running`] if the process is still running,
    /// [`RunningState::Terminated`] if it has exited, or [`RunningState::Uncertain`]
    /// if the state could not be determined.
    //noinspection RsSelfConvention
    pub fn is_running(&mut self) -> RunningState {
        match self.try_reap_exit_status() {
            Ok(None) => RunningState::Running,
            Ok(Some(exit_status)) => RunningState::Terminated(exit_status),
            Err(err) => RunningState::Uncertain(err),
        }
    }

    /// Returns a mutable reference to the (potentially already closed) stdin stream.
    ///
    /// Use this to write data to the child process's stdin. The stdin stream implements
    /// [`tokio::io::AsyncWrite`], allowing you to use methods like `write_all()` and `flush()`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use tokio::process::Command;
    /// # use tokio_process_tools::*;
    /// # use tokio::io::AsyncWriteExt;
    /// # tokio_test::block_on(async {
    /// // Whether we `spawn_broadcast` or `spawn_single_subscriber` does not make a difference here.
    /// let mut process = Process::new(Command::new("cat"))
    ///     .spawn_broadcast()
    ///     .unwrap();
    ///
    /// // Write to stdin.
    /// if let Some(stdin) = process.stdin().as_mut() {
    ///     stdin.write_all(b"Hello, process!\n").await.unwrap();
    ///     stdin.flush().await.unwrap();
    /// }
    ///
    /// // Close stdin to signal EOF.
    /// process.stdin().close();
    /// # });
    /// ```
    pub fn stdin(&mut self) -> &mut Stdin {
        &mut self.std_in
    }

    /// Returns a reference to the stdout stream.
    ///
    /// For `BroadcastOutputStream`, this allows creating multiple concurrent consumers.
    /// For `SingleSubscriberOutputStream`, only one consumer can be created (subsequent
    /// attempts will panic with a helpful error message).
    pub fn stdout(&self) -> &O {
        &self.std_out_stream
    }

    /// Returns a reference to the stderr stream.
    ///
    /// For `BroadcastOutputStream`, this allows creating multiple concurrent consumers.
    /// For `SingleSubscriberOutputStream`, only one consumer can be created (subsequent
    /// attempts will panic with a helpful error message).
    pub fn stderr(&self) -> &O {
        &self.std_err_stream
    }

    /// Sets a panic-on-drop mechanism for this `ProcessHandle`.
    ///
    /// This method enables a safeguard that ensures that the process represented by this
    /// `ProcessHandle` is properly terminated or awaited before being dropped.
    /// If `must_be_terminated` is set and the `ProcessHandle` is
    /// dropped without invoking `terminate()` or `wait()`, an intentional panic will occur to
    /// prevent silent failure-states, ensuring that system resources are handled correctly.
    ///
    /// You typically do not need to call this, as every `ProcessHandle` is marked by default.
    /// Call `must_not_be_terminated` to clear this safeguard to explicitly allow dropping the
    /// process without terminating it.
    ///
    /// # Panic
    ///
    /// If the `ProcessHandle` is dropped without being awaited or terminated
    /// after calling this method, a panic will occur with a descriptive message
    /// to inform about the incorrect usage.
    pub fn must_be_terminated(&mut self) {
        self.cleanup_on_drop = true;
        self.panic_on_drop = Some(PanicOnDrop::new(
            "tokio_process_tools::ProcessHandle",
            "The process was not terminated.",
            "Call `wait_for_completion` or `terminate` before the type is dropped!",
        ));
    }

    /// Disables the kill/panic-on-drop safeguards for this handle.
    ///
    /// Dropping the handle after calling this method will no longer signal, kill, or panic.
    /// However, this does **not** keep the library-owned stdio pipes alive. If the child still
    /// depends on stdin, stdout, or stderr being open, dropping the handle may still affect it.
    ///
    /// Use plain [`tokio::process::Command`] directly when you need a child process that can
    /// outlive the original handle without depending on captured stdio pipes.
    pub fn must_not_be_terminated(&mut self) {
        self.cleanup_on_drop = false;
        self.defuse_drop_panic();
    }

    fn defuse_drop_panic(&mut self) {
        if let Some(mut it) = self.panic_on_drop.take() {
            it.defuse();
        }
    }

    /// Wrap this process handle in a `TerminateOnDrop` instance, terminating the controlled process
    /// automatically when this handle is dropped.
    ///
    /// **SAFETY: This only works when your code is running in a multithreaded tokio runtime!**
    ///
    /// Prefer manual termination of the process or awaiting it and relying on the (automatically
    /// configured) `must_be_terminated` logic, raising a panic when a process was neither awaited
    /// nor terminated before being dropped.
    pub fn terminate_on_drop(
        self,
        graceful_termination_timeout: Duration,
        forceful_termination_timeout: Duration,
    ) -> TerminateOnDrop<O> {
        TerminateOnDrop {
            process_handle: self,
            interrupt_timeout: graceful_termination_timeout,
            terminate_timeout: forceful_termination_timeout,
        }
    }

    /// Manually send a `SIGINT` on unix or equivalent on Windows to this process.
    ///
    /// Prefer to call `terminate` instead, if you want to make sure this process is terminated.
    ///
    /// # Errors
    ///
    /// Returns an error if the platform signal could not be sent.
    pub fn send_interrupt_signal(&mut self) -> Result<(), io::Error> {
        signal::send_interrupt(&self.child)
    }

    /// Manually send a `SIGTERM` on unix or equivalent on Windows to this process.
    ///
    /// Prefer to call `terminate` instead, if you want to make sure this process is terminated.
    ///
    /// # Errors
    ///
    /// Returns an error if the platform signal could not be sent.
    pub fn send_terminate_signal(&mut self) -> Result<(), io::Error> {
        signal::send_terminate(&self.child)
    }

    /// Terminates this process by sending a `SIGINT`, `SIGTERM` or even a `SIGKILL` if the process
    /// doesn't run to completion after receiving any of the first two signals.
    ///
    /// This handle can be dropped safely after this call returned, no matter the outcome.
    /// We accept that in extremely rare cases, failed `SIGKILL`, a rogue process may be left over.
    ///
    /// # Errors
    ///
    /// Returns [`TerminationError`] if signalling or waiting for process termination fails.
    pub async fn terminate(
        &mut self,
        interrupt_timeout: Duration,
        terminate_timeout: Duration,
    ) -> Result<ExitStatus, TerminationError> {
        // Whether or not this function will ultimately succeed, we tried our best to terminate
        // this process.
        // Dropping this handle should not create any on-drop panic anymore.
        // We accept that in extremely rare cases, failed `kill`, a rogue process may be left over.
        self.defuse_drop_panic();

        if let Some(exit_status) =
            self.try_reap_exit_status()
                .map_err(|source| TerminationError::SignallingFailed {
                    process_name: self.name.clone(),
                    source,
                    signal: "SIGINT",
                })?
        {
            return Ok(exit_status);
        }

        if let Err(err) = self.send_interrupt_signal() {
            return self.signalling_failed_or_reap("SIGINT", err);
        }

        match self.wait_for_completion(Some(interrupt_timeout)).await {
            Ok(exit_status) => Ok(exit_status),
            Err(not_terminated_after_sigint) => {
                tracing::warn!(
                    process = %self.name,
                    error = %not_terminated_after_sigint,
                    "Graceful shutdown using SIGINT (or equivalent on current platform) failed. Attempting graceful shutdown using SIGTERM signal."
                );

                if let Err(err) = self.send_terminate_signal() {
                    return self.signalling_failed_or_reap("SIGTERM", err);
                }

                match self.wait_for_completion(Some(terminate_timeout)).await {
                    Ok(exit_status) => Ok(exit_status),
                    Err(not_terminated_after_sigterm) => {
                        tracing::warn!(
                            process = %self.name,
                            error = %not_terminated_after_sigterm,
                            "Graceful shutdown using SIGTERM (or equivalent on current platform) failed. Attempting forceful shutdown using SIGKILL signal."
                        );

                        match self.kill().await {
                            Ok(()) => {
                                // Note: A SIGKILL should typically (somewhat) immediately lead to
                                // termination of the process. But there are cases in which even
                                // a SIGKILL does not / cannot / will not kill a process.
                                // Something must have gone horribly wrong then...
                                // But: We do not want to wait indefinitely in case this happens
                                // and therefore wait (at max) for a fixed duration after any
                                // SIGKILL event.
                                match self.wait_for_completion(Some(SIGKILL_WAIT_TIMEOUT)).await {
                                    Ok(exit_status) => Ok(exit_status),
                                    Err(not_terminated_after_sigkill) => {
                                        // Unlikely. See the note above.
                                        tracing::error!(
                                            "Process, having custom name '{}', did not terminate after receiving a SIGINT, SIGTERM and SIGKILL event (or equivalent on the current platform). Something must have gone horribly wrong... Process may still be running. Manual intervention and investigation required!",
                                            self.name
                                        );
                                        Err(TerminationError::TerminationFailed {
                                            process_name: self.name.clone(),
                                            sigint_error: not_terminated_after_sigint.to_string(),
                                            sigterm_error: not_terminated_after_sigterm.to_string(),
                                            sigkill_error: io::Error::new(
                                                io::ErrorKind::TimedOut,
                                                not_terminated_after_sigkill.to_string(),
                                            ),
                                        })
                                    }
                                }
                            }
                            Err(kill_error) => {
                                if let Ok(Some(exit_status)) = self.try_reap_exit_status() {
                                    return Ok(exit_status);
                                }
                                tracing::error!(
                                    process = %self.name,
                                    error = %kill_error,
                                    "Forceful shutdown using SIGKILL (or equivalent on current platform) failed. Process may still be running. Manual intervention required!"
                                );

                                Err(TerminationError::TerminationFailed {
                                    process_name: self.name.clone(),
                                    sigint_error: not_terminated_after_sigint.to_string(),
                                    sigterm_error: not_terminated_after_sigterm.to_string(),
                                    sigkill_error: kill_error,
                                })
                            }
                        }
                    }
                }
            }
        }
    }

    /// Forces the process to exit. Most users should call [`ProcessHandle::terminate`] instead.
    ///
    /// This is equivalent to sending a SIGKILL on unix platforms followed by wait.
    ///
    /// # Errors
    ///
    /// Returns an error if Tokio cannot kill the child process.
    pub async fn kill(&mut self) -> io::Result<()> {
        self.child.kill().await
    }

    /// Successfully awaiting the completion of the process will unset the
    /// "must be terminated" setting, as a successfully awaited process is already terminated.
    /// Dropping this `ProcessHandle` after successfully calling `wait` should never lead to a
    /// "must be terminated" panic being raised.
    async fn wait(&mut self) -> io::Result<ExitStatus> {
        match self.child.wait().await {
            Ok(status) => {
                self.must_not_be_terminated();
                Ok(status)
            }
            Err(err) => Err(err),
        }
    }

    /// Wait for this process to run to completion. Within `timeout`, if set, or unbound otherwise.
    ///
    /// If the timeout is reached before the process terminated, an error is returned but the
    /// process remains untouched / keeps running.
    /// Use [`ProcessHandle::wait_for_completion_or_terminate`] if you want immediate termination.
    ///
    /// This does not provide the processes output. You can take a look at the convenience function
    /// [`ProcessHandle::<BroadcastOutputStream>::wait_for_completion_with_output`] to see
    /// how the [`ProcessHandle::stdout`] and [`ProcessHandle::stderr`] streams (also available in
    /// *_mut variants) can be used to inspect / watch over / capture the processes output.
    ///
    /// # Errors
    ///
    /// Returns [`WaitError`] if waiting for the process fails or the timeout elapses.
    pub async fn wait_for_completion(
        &mut self,
        timeout: Option<Duration>,
    ) -> Result<ExitStatus, WaitError> {
        match timeout {
            None => self.wait().await.map_err(|source| WaitError::IoError {
                process_name: self.name.clone(),
                source,
            }),
            Some(timeout_duration) => {
                match tokio::time::timeout(timeout_duration, self.wait()).await {
                    Ok(Ok(exit_status)) => Ok(exit_status),
                    Ok(Err(source)) => Err(WaitError::IoError {
                        process_name: self.name.clone(),
                        source,
                    }),
                    Err(_elapsed) => Err(WaitError::Timeout {
                        process_name: self.name.clone(),
                        timeout: timeout_duration,
                    }),
                }
            }
        }
    }

    /// Wait for this process to run to completion within `timeout`.
    ///
    /// If the timeout is reached before the process terminated normally, external termination of
    /// the process is forced through [`ProcessHandle::terminate`].
    ///
    /// Note that this function may return `Ok` even though the timeout was reached, carrying the
    /// exit status received after sending a termination signal!
    ///
    /// # Errors
    ///
    /// Returns [`TerminationError`] if termination is required and then fails.
    pub async fn wait_for_completion_or_terminate(
        &mut self,
        wait_timeout: Duration,
        interrupt_timeout: Duration,
        terminate_timeout: Duration,
    ) -> Result<ExitStatus, TerminationError> {
        match self.wait_for_completion(Some(wait_timeout)).await {
            Ok(exit_status) => Ok(exit_status),
            Err(_err) => self.terminate(interrupt_timeout, terminate_timeout).await,
        }
    }

    /// Consumes this handle to provide the wrapped `tokio::process::Child` instance as well as the
    /// stdout and stderr output streams.
    pub fn into_inner(mut self) -> (Child, O, O) {
        self.must_not_be_terminated();
        let mut this = std::mem::ManuallyDrop::new(self);

        unsafe {
            let child = std::ptr::read(&raw const this.child);
            let stdout = std::ptr::read(&raw const this.std_out_stream);
            let stderr = std::ptr::read(&raw const this.std_err_stream);

            std::ptr::drop_in_place(&raw mut this.name);
            // `ChildStdin` is stored separately from `child`, so we still need to drop it here.
            std::ptr::drop_in_place(&raw mut this.std_in);
            std::ptr::drop_in_place(&raw mut this.panic_on_drop);

            (child, stdout, stderr)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use assertr::prelude::*;
    use std::fs;
    use std::sync::{Arc, Mutex};
    use tokio::io::AsyncWriteExt;

    use crate::Next;

    #[tokio::test]
    async fn test_termination() {
        let mut cmd = tokio::process::Command::new("sleep");
        cmd.arg("5");

        let started_at = jiff::Zoned::now();
        let mut handle = crate::Process::new(cmd)
            .name("sleep")
            .spawn_broadcast()
            .unwrap();
        tokio::time::sleep(Duration::from_millis(100)).await;
        let exit_status = handle
            .terminate(Duration::from_secs(1), Duration::from_secs(1))
            .await
            .unwrap();
        let terminated_at = jiff::Zoned::now();

        // We terminate after roughly 100 ms of waiting.
        // Let's use a 50 ms grace period on the assertion taken up by performing the termination.
        // We can increase this if the test should turn out to be flaky.
        let ran_for = started_at.duration_until(&terminated_at);
        assert_that!(ran_for.as_secs_f32()).is_close_to(0.1, 0.5);

        // When terminated, we do not get an exit code (unix).
        assert_that!(exit_status.code()).is_none();
    }

    #[tokio::test]
    async fn terminate_returns_normal_exit_when_process_already_exited() {
        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c").arg("exit 0");

        let mut handle = crate::Process::new(cmd)
            .name("sh")
            .spawn_broadcast()
            .unwrap();

        tokio::time::sleep(Duration::from_millis(50)).await;

        let exit_status = handle
            .terminate(Duration::from_millis(50), Duration::from_millis(50))
            .await
            .unwrap();

        assert_that!(exit_status.success()).is_true();
    }

    #[tokio::test]
    async fn test_stdin_write_and_read() {
        let cmd = tokio::process::Command::new("cat");
        let mut process = crate::Process::new(cmd)
            .name("cat")
            .spawn_broadcast()
            .unwrap();

        // Verify stdin starts as open.
        assert_that!(process.stdin().is_open()).is_true();

        // Write to stdin.
        let test_data = b"Hello from stdin!\n";
        if let Some(stdin) = process.stdin().as_mut() {
            stdin.write_all(test_data).await.unwrap();
            stdin.flush().await.unwrap();
        }

        // Close stdin to signal EOF.
        process.stdin().close();
        assert_that!(process.stdin().is_open()).is_false();

        // Collect stdout.
        let output = process
            .wait_for_completion_with_output(
                Some(Duration::from_secs(2)),
                LineParsingOptions::default(),
            )
            .await
            .unwrap();

        assert_that!(output.status.success()).is_true();
        assert_that!(&output.stdout).has_length(1);
        assert_that!(output.stdout[0].as_str()).is_equal_to("Hello from stdin!");
    }

    #[tokio::test]
    async fn test_stdin_close_sends_eof() {
        // Use `cat` which will exit when stdin is closed.
        let cmd = tokio::process::Command::new("cat");
        let mut process = crate::Process::new(cmd)
            .name("cat")
            .spawn_broadcast()
            .unwrap();

        // Close stdin immediately without writing.
        process.stdin().close();
        assert_that!(process.stdin().is_open()).is_false();

        // Process should terminate since it receives EOF.
        let status = process
            .wait_for_completion(Some(Duration::from_secs(2)))
            .await
            .unwrap();

        assert_that!(status.success()).is_true();
    }

    #[tokio::test]
    async fn test_stdin_multiple_writes() {
        let cmd = tokio::process::Command::new("cat");
        let mut process = crate::Process::new(cmd)
            .name("cat")
            .spawn_broadcast()
            .unwrap();

        // Write multiple lines.
        if let Some(stdin) = process.stdin().as_mut() {
            stdin.write_all(b"Line 1\n").await.unwrap();
            stdin.write_all(b"Line 2\n").await.unwrap();
            stdin.write_all(b"Line 3\n").await.unwrap();
            stdin.flush().await.unwrap();
        }

        process.stdin().close();

        let output = process
            .wait_for_completion_with_output(
                Some(Duration::from_secs(2)),
                LineParsingOptions::default(),
            )
            .await
            .unwrap();

        assert_that!(&output.stdout).has_length(3);
        assert_that!(output.stdout[0].as_str()).is_equal_to("Line 1");
        assert_that!(output.stdout[1].as_str()).is_equal_to("Line 2");
        assert_that!(output.stdout[2].as_str()).is_equal_to("Line 3");
    }

    #[tokio::test]
    async fn test_shell_command_dispatch() {
        let cmd = tokio::process::Command::new("sh");

        let mut process = crate::Process::new(cmd).spawn_broadcast().unwrap();

        // Monitor output.
        let collector = process
            .stdout()
            .collect_lines_into_vec(LineParsingOptions::default());

        // Send commands to the shell.
        if let Some(stdin) = process.stdin().as_mut() {
            stdin
                .write_all(b"printf 'Hello from shell\\n'\nexit\n")
                .await
                .unwrap();
            stdin.flush().await.unwrap();
        }

        // Wait a bit for output.
        tokio::time::sleep(Duration::from_millis(500)).await;

        process.stdin().close();
        process
            .wait_for_completion(Some(Duration::from_secs(1)))
            .await
            .unwrap();

        let collected = collector.wait().await.unwrap();
        assert_that!(&collected).has_length(1);
        assert_that!(collected[0].as_str()).is_equal_to("Hello from shell");
    }

    #[tokio::test]
    async fn test_into_inner_defuses_panic_guard() {
        let mut cmd = tokio::process::Command::new("sleep");
        cmd.arg("5");

        let process = crate::Process::new(cmd)
            .name("sleep")
            .spawn_broadcast()
            .unwrap();

        let (mut child, _stdout, _stderr) = process.into_inner();
        child.kill().await.unwrap();
        let _status = child.wait().await.unwrap();
    }

    #[tokio::test]
    async fn test_into_inner_with_owned_name_drops_owned_string() {
        // Regression test: `into_inner` manually destructures the handle through
        // `ManuallyDrop`. If the `name` field isn't explicitly dropped, a
        // `Cow::Owned(String)` allocation leaks. Forcing the owned variant here
        // exercises the path that the static-`&str` test above doesn't.
        let mut cmd = tokio::process::Command::new("sleep");
        cmd.arg("5");

        let process = crate::Process::new(cmd)
            .with_name(format!("sleeper-{}", 7))
            .spawn_broadcast()
            .unwrap();

        let (mut child, _stdout, _stderr) = process.into_inner();
        child.kill().await.unwrap();
        let _status = child.wait().await.unwrap();
    }

    #[tokio::test]
    async fn test_defusing_drop_panic_keeps_cleanup_guard_armed() {
        let mut cmd = tokio::process::Command::new("sleep");
        cmd.arg("5");

        let mut process = crate::Process::new(cmd)
            .name("sleep")
            .spawn_broadcast()
            .unwrap();

        assert_that!(process.cleanup_on_drop).is_true();
        assert_that!(
            process
                .panic_on_drop
                .as_ref()
                .is_some_and(PanicOnDrop::is_armed)
        )
        .is_true();

        process.defuse_drop_panic();

        assert_that!(process.cleanup_on_drop).is_true();
        assert_that!(&process.panic_on_drop).is_none();

        process.kill().await.unwrap();
        process.wait_for_completion(None).await.unwrap();
    }

    #[tokio::test]
    async fn test_wait_for_completion_disarms_cleanup_and_panic_guards() {
        let mut cmd = tokio::process::Command::new("sleep");
        cmd.arg("0.1");

        let mut process = crate::Process::new(cmd)
            .name("sleep")
            .spawn_broadcast()
            .unwrap();

        process
            .wait_for_completion(Some(Duration::from_secs(2)))
            .await
            .unwrap();

        assert_that!(process.cleanup_on_drop).is_false();
        assert_that!(&process.panic_on_drop).is_none();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_must_not_be_terminated_allows_process_to_survive_handle_drop() {
        use nix::errno::Errno;
        use nix::sys::signal::{self, Signal};
        use nix::sys::wait::waitpid;
        use nix::unistd::Pid;

        let mut cmd = tokio::process::Command::new("sleep");
        cmd.arg("5");

        let mut process = crate::Process::new(cmd)
            .name("sleep")
            .spawn_broadcast()
            .unwrap();
        let pid = process.id().unwrap();

        process.must_not_be_terminated();
        assert_that!(process.cleanup_on_drop).is_false();
        assert_that!(&process.panic_on_drop).is_none();
        drop(process);

        let pid = Pid::from_raw(pid.cast_signed());
        assert_that!(signal::kill(pid, None).is_ok()).is_true();

        signal::kill(pid, Signal::SIGKILL).unwrap();
        match waitpid(pid, None) {
            Ok(_) | Err(Errno::ECHILD) => {}
            Err(err) => panic!("waitpid failed: {err}"),
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_must_not_be_terminated_still_closes_stdin_on_drop() {
        use nix::sys::wait::waitpid;
        use nix::unistd::Pid;
        use tempfile::tempdir;

        let temp_dir = tempdir().unwrap();
        let output_file = temp_dir.path().join("stdin-result.txt");
        let output_file = output_file.to_str().unwrap().replace('\'', "'\"'\"'");

        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c")
            .arg(format!("cat >/dev/null; printf eof > '{output_file}'"));

        let mut process = crate::Process::new(cmd)
            .name("sh")
            .spawn_broadcast()
            .unwrap();
        let pid = Pid::from_raw(process.id().unwrap().cast_signed());

        process.must_not_be_terminated();
        drop(process);

        tokio::time::timeout(
            Duration::from_secs(2),
            tokio::task::spawn_blocking(move || waitpid(pid, None)),
        )
        .await
        .unwrap()
        .unwrap()
        .unwrap();

        assert_that!(fs::read_to_string(temp_dir.path().join("stdin-result.txt")).unwrap())
            .is_equal_to("eof");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_must_not_be_terminated_does_not_keep_stdout_pipe_alive() {
        use nix::sys::wait::waitpid;
        use nix::unistd::Pid;

        let mut cmd = tokio::process::Command::new("yes");
        cmd.arg("tick");

        let mut process = crate::Process::new(cmd)
            .name("yes")
            .spawn_broadcast()
            .unwrap();
        let pid = Pid::from_raw(process.id().unwrap().cast_signed());

        process.must_not_be_terminated();
        drop(process);

        tokio::time::timeout(
            Duration::from_secs(2),
            tokio::task::spawn_blocking(move || waitpid(pid, None)),
        )
        .await
        .unwrap()
        .unwrap()
        .unwrap();
    }

    #[tokio::test]
    async fn test_wait_for_completion_with_output_preserves_unterminated_final_line() {
        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c").arg("printf tail");

        let mut process = crate::Process::new(cmd)
            .name("sh")
            .spawn_broadcast()
            .unwrap();

        let output = process
            .wait_for_completion_with_output(
                Some(Duration::from_secs(2)),
                LineParsingOptions::default(),
            )
            .await
            .unwrap();

        assert_that!(output.status.success()).is_true();
        assert_that!(output.stdout).contains_exactly(["tail"]);
        assert_that!(output.stderr).is_empty();
    }

    #[tokio::test]
    async fn test_broadcast_wait_for_completion_with_raw_output_preserves_bytes() {
        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c")
            .arg("printf 'out\nraw'; printf 'err\nraw' >&2");

        let mut process = crate::Process::new(cmd)
            .name("sh")
            .spawn_broadcast()
            .unwrap();

        let output = process
            .wait_for_completion_with_raw_output(Some(Duration::from_secs(2)))
            .await
            .unwrap();

        assert_that!(output.status.success()).is_true();
        assert_that!(output.stdout).is_equal_to(b"out\nraw".to_vec());
        assert_that!(output.stderr).is_equal_to(b"err\nraw".to_vec());
    }

    #[tokio::test]
    async fn test_single_subscriber_wait_for_completion_with_raw_output_preserves_bytes() {
        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c")
            .arg("printf 'out\nraw'; printf 'err\nraw' >&2");

        let mut process = crate::Process::new(cmd)
            .name("sh")
            .spawn_single_subscriber()
            .unwrap();

        let output = process
            .wait_for_completion_with_raw_output(Some(Duration::from_secs(2)))
            .await
            .unwrap();

        assert_that!(output.status.success()).is_true();
        assert_that!(output.stdout).is_equal_to(b"out\nraw".to_vec());
        assert_that!(output.stderr).is_equal_to(b"err\nraw".to_vec());
    }

    #[tokio::test]
    async fn test_inspect_lines_async_preserves_unterminated_final_line() {
        let mut cmd = tokio::process::Command::new("sh");
        cmd.arg("-c").arg("printf tail");

        let mut process = crate::Process::new(cmd)
            .name("sh")
            .spawn_broadcast()
            .unwrap();

        let seen = Arc::new(Mutex::new(Vec::<String>::new()));
        let seen_in_task = Arc::clone(&seen);
        let inspector = process.stdout().inspect_lines_async(
            move |line| {
                let seen = Arc::clone(&seen_in_task);
                let line = line.into_owned();
                async move {
                    seen.lock().expect("lock").push(line);
                    Next::Continue
                }
            },
            LineParsingOptions::default(),
        );

        process
            .wait_for_completion(Some(Duration::from_secs(2)))
            .await
            .unwrap();
        inspector.wait().await.unwrap();

        let seen = seen.lock().expect("lock").clone();
        assert_that!(seen).contains_exactly(["tail"]);
    }
}