carte 0.6.0

Runs your apps' processes on demand behind *.localhost hostnames, one stack per git worktree
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
mod common;

use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::os::unix::process::ExitStatusExt;
use std::path::Path;
use std::process::ExitStatus;
use std::time::{Duration, Instant};

use carte::process::{IoMode, Output, ProcessHandle, SpawnSpec, Spawner};
use common::{fixture, guard, lifeline};
use nix::sys::signal::{Signal, kill};
use nix::unistd::Pid;
use tokio::io::AsyncReadExt;

fn spawner() -> Spawner {
    Spawner::new(env!("CARGO_BIN_EXE_carte"))
}

fn free_port() -> u16 {
    carte::supervisor::runner::use_test_ports();
    carte::supervisor::runner::free_port().unwrap()
}

fn spec() -> SpawnSpec {
    SpawnSpec::new(fixture().display().to_string(), std::env::temp_dir())
        .env("FIXTURE_LIFELINE_PID", lifeline())
}

async fn read_until(output: &mut Output, seen: &mut Vec<u8>, needle: &str) {
    let found = tokio::time::timeout(Duration::from_secs(10), async {
        let mut buf = [0u8; 4096];
        while !String::from_utf8_lossy(seen).contains(needle) {
            let n = output.read(&mut buf).await.unwrap();
            assert!(n > 0, "EOF before {needle:?}");
            seen.extend_from_slice(&buf[..n]);
        }
    })
    .await;
    assert!(
        found.is_ok(),
        "timed out waiting for {needle:?}, got {:?}",
        String::from_utf8_lossy(seen)
    );
}

async fn read_to_end(output: &mut Output) -> String {
    let mut seen = Vec::new();
    tokio::time::timeout(Duration::from_secs(10), output.read_to_end(&mut seen))
        .await
        .expect("output EOF")
        .unwrap();
    String::from_utf8_lossy(&seen).into_owned()
}

async fn run_to_end(handle: &mut ProcessHandle) -> (ExitStatus, String) {
    let mut output = handle.take_output().unwrap();
    let (status, text) = tokio::join!(handle.wait(), read_to_end(&mut output));
    (status.unwrap(), text)
}

fn drain(mut output: Output) {
    tokio::spawn(async move { while output.read(&mut [0u8; 4096]).await.is_ok_and(|n| n > 0) {} });
}

fn alive(pid: u32) -> bool {
    kill(Pid::from_raw(pid as i32), None).is_ok()
}

async fn wait_dead(pid: u32) {
    let deadline = Instant::now() + Duration::from_secs(10);
    while alive(pid) {
        assert!(Instant::now() < deadline, "pid {pid} still alive");
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

async fn read_pidfile(path: &Path) -> u32 {
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        if let Ok(s) = std::fs::read_to_string(path)
            && let Ok(pid) = s.trim().parse()
        {
            return pid;
        }
        assert!(
            Instant::now() < deadline,
            "no pidfile at {}",
            path.display()
        );
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

async fn stop(mut handle: ProcessHandle) {
    handle.stop(Duration::from_secs(2)).await.unwrap();
}

#[tokio::test]
async fn pty_output_is_line_buffered_and_a_tty() {
    let mut handle = spawner()
        .spawn(
            &spec()
                .env("FIXTURE_LINES", "3")
                .env("FIXTURE_PARTIAL", "partial>"),
        )
        .await
        .unwrap();
    assert_ne!(handle.pid(), handle.shim_pid());
    let mut output = handle.take_output().unwrap();
    let mut seen = Vec::new();
    read_until(&mut output, &mut seen, "partial>").await;
    drain(output);
    let text = String::from_utf8_lossy(&seen);
    assert!(
        text.starts_with("tty: true\r\nline 1\r\nline 2\r\nline 3\r\n"),
        "{text:?}"
    );
    assert!(alive(handle.pid()));
    stop(handle).await;
}

#[tokio::test]
async fn pipe_mode_merges_output_without_a_tty() {
    let mut handle = spawner()
        .spawn(
            &spec()
                .io(IoMode::Pipes)
                .env("FIXTURE_LINES", "2")
                .env("FIXTURE_CRASH", "4"),
        )
        .await
        .unwrap();
    let (status, text) = run_to_end(&mut handle).await;
    assert!(text.contains("tty: false\nline 1\nline 2\n"), "{text:?}");
    assert!(text.contains("crashing with 4\n"), "{text:?}");
    assert_eq!(status.code(), Some(4));
}

#[tokio::test]
async fn crash_output_survives_exit_on_a_pty() {
    let mut handle = spawner()
        .spawn(&spec().env("FIXTURE_LINES", "50").env("FIXTURE_CRASH", "3"))
        .await
        .unwrap();
    let (status, text) = run_to_end(&mut handle).await;
    assert_eq!(status.code(), Some(3));
    assert!(text.contains("line 50\r\n"), "{text:?}");
    assert!(text.contains("crashing with 3"), "{text:?}");
}

#[tokio::test]
async fn pty_input_reaches_the_foreground_group() {
    let mut handle = spawner()
        .spawn(&spec().env("FIXTURE_ECHO_STDIN", "1"))
        .await
        .unwrap();
    let mut output = handle.take_output().unwrap();
    let mut seen = Vec::new();
    read_until(&mut output, &mut seen, "ready").await;
    handle.write_input(b"hello\n").await.unwrap();
    read_until(&mut output, &mut seen, "echo: hello").await;
    drain(output);
    stop(handle).await;
}

#[tokio::test]
async fn command_runs_with_given_env_and_cwd() {
    let dir = tempfile::tempdir().unwrap();
    let mut handle = spawner()
        .spawn(
            &SpawnSpec::new("echo \"$GREETING from $(pwd -P)\"", dir.path()).env("GREETING", "hi"),
        )
        .await
        .unwrap();
    let (status, text) = run_to_end(&mut handle).await;
    let cwd = dir.path().canonicalize().unwrap();
    assert_eq!(text, format!("hi from {}\r\n", cwd.display()));
    assert!(status.success());
}

#[tokio::test]
async fn serves_http_on_port() {
    for ipv6 in [false, true] {
        let port = free_port();
        let mut spec = spec()
            .env("PORT", port.to_string())
            .env("FIXTURE_NAME", "web")
            .env("FIXTURE_ENV", "PORT,MISSING");
        if ipv6 {
            spec = spec.env("FIXTURE_BIND", "::1");
        }
        let mut handle = spawner().spawn(&spec).await.unwrap();
        let mut output = handle.take_output().unwrap();
        read_until(&mut output, &mut Vec::new(), "ready").await;
        drain(output);

        let host = if ipv6 {
            format!("[::1]:{port}")
        } else {
            format!("127.0.0.1:{port}")
        };
        assert!(get(&host, "/up").ends_with("\r\n\r\nok"));
        let body = get(&host, "/");
        let expected = format!(
            r#"{{"name":"web","pid":{},"env":{{"PORT":"{port}","MISSING":null}}}}"#,
            handle.pid()
        );
        assert!(body.ends_with(&expected), "{body}");
        stop(handle).await;
    }
}

fn get(host: &str, path: &str) -> String {
    let mut stream = TcpStream::connect(host).unwrap();
    write!(stream, "GET {path} HTTP/1.1\r\nHost: x\r\n\r\n").unwrap();
    let mut response = String::new();
    stream.read_to_string(&mut response).unwrap();
    response
}

#[tokio::test]
async fn stop_terminates_the_group() {
    let mut handle = spawner().spawn(&spec()).await.unwrap();
    drain(handle.take_output().unwrap());
    let pid = handle.pid();
    let started = Instant::now();
    let status = handle.stop(Duration::from_secs(5)).await.unwrap();
    assert_eq!(status.signal(), Some(libc::SIGTERM));
    assert!(started.elapsed() < Duration::from_secs(2));
    assert!(!alive(pid));
    assert!(handle.signal_group(Signal::SIGTERM).is_err());
}

#[tokio::test]
async fn stop_escalates_to_kill() {
    let mut handle = spawner()
        .spawn(&spec().env("FIXTURE_IGNORE_TERM", "1"))
        .await
        .unwrap();
    let mut output = handle.take_output().unwrap();
    read_until(&mut output, &mut Vec::new(), "ready").await;
    drain(output);
    let started = Instant::now();
    let status = handle.stop(Duration::from_millis(300)).await.unwrap();
    assert_eq!(status.signal(), Some(libc::SIGKILL));
    assert!(started.elapsed() >= Duration::from_millis(300));
}

#[tokio::test]
async fn suspend_character_on_the_pty_does_not_stop_the_app() {
    let port = free_port();
    let mut handle = spawner()
        .spawn(&spec().env("PORT", port.to_string()))
        .await
        .unwrap();
    let mut output = handle.take_output().unwrap();
    read_until(&mut output, &mut Vec::new(), "ready").await;
    drain(output);
    handle.write_input(b"\x1a").await.unwrap();
    tokio::time::sleep(Duration::from_millis(200)).await;
    let host = format!("127.0.0.1:{port}");
    let response = tokio::task::spawn_blocking(move || {
        let mut stream = TcpStream::connect(host).unwrap();
        stream
            .set_read_timeout(Some(Duration::from_secs(3)))
            .unwrap();
        write!(stream, "GET /up HTTP/1.1\r\nHost: x\r\n\r\n").unwrap();
        let mut response = String::new();
        stream.read_to_string(&mut response).map(|_| response)
    })
    .await
    .unwrap();
    assert!(
        response.as_ref().is_ok_and(|r| r.ends_with("\r\n\r\nok")),
        "{response:?}"
    );
    stop(handle).await;
}

/// Waits until `pid` is stopped.
async fn wait_stopped(pid: u32) {
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let ps = std::process::Command::new("ps")
            .args(["-o", "stat=", "-p", &pid.to_string()])
            .output()
            .unwrap();
        if String::from_utf8_lossy(&ps.stdout)
            .trim_start()
            .starts_with('T')
        {
            return;
        }
        assert!(Instant::now() < deadline, "pid {pid} not stopped");
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

/// A command that leaves `marker` behind when SIGTERM reaches its handler.
fn trapping_term(marker: &Path) -> SpawnSpec {
    SpawnSpec::new(
        format!(
            "trap 'touch {}; exit 3' TERM; echo ready; while :; do sleep 0.1; done",
            marker.display()
        ),
        std::env::temp_dir(),
    )
}

#[tokio::test]
async fn stop_resumes_a_stopped_group() {
    let dir = tempfile::tempdir().unwrap();
    let marker = dir.path().join("terminated");
    let mut handle = spawner().spawn(&trapping_term(&marker)).await.unwrap();
    let mut output = handle.take_output().unwrap();
    read_until(&mut output, &mut Vec::new(), "ready").await;
    drain(output);
    handle.signal_group(Signal::SIGSTOP).unwrap();
    wait_stopped(handle.pid()).await;
    let started = Instant::now();
    let status = handle.stop(Duration::from_secs(5)).await.unwrap();
    assert_eq!(status.code(), Some(3));
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "{:?}",
        started.elapsed()
    );
    assert!(marker.exists());
}

#[tokio::test]
async fn closing_the_lifeline_resumes_a_stopped_group() {
    let dir = tempfile::tempdir().unwrap();
    let marker = dir.path().join("terminated");
    let mut handle = spawner().spawn(&trapping_term(&marker)).await.unwrap();
    let mut output = handle.take_output().unwrap();
    read_until(&mut output, &mut Vec::new(), "ready").await;
    drain(output);
    handle.signal_group(Signal::SIGSTOP).unwrap();
    wait_stopped(handle.pid()).await;
    handle.close_lifeline();
    tokio::time::timeout(Duration::from_secs(10), handle.wait())
        .await
        .unwrap()
        .unwrap();
    assert!(marker.exists());
}

#[tokio::test]
async fn a_group_that_suspends_itself_is_resumed() {
    let mut handle = spawner()
        .spawn(&SpawnSpec::new(
            "echo ready; kill -TSTP 0; echo resumed",
            std::env::temp_dir(),
        ))
        .await
        .unwrap();
    let mut output = handle.take_output().unwrap();
    read_until(&mut output, &mut Vec::new(), "resumed").await;
    drain(output);
    assert!(handle.wait().await.unwrap().success());
}

#[tokio::test]
async fn a_command_stopped_by_a_signal_is_reported_until_it_continues() {
    let dir = tempfile::tempdir().unwrap();
    let go = dir.path().join("go");
    let done = dir.path().join("done");
    let mut handle = spawner()
        .spawn(&SpawnSpec::new(
            "(while [ ! -e go ]; do sleep 0.05; done; kill -CONT $$) & kill -STOP $$; while [ ! -e done ]; do sleep 0.05; done",
            dir.path(),
        ))
        .await
        .unwrap();
    drain(handle.take_output().unwrap());
    let mut reports = Vec::new();
    let status = tokio::time::timeout(
        Duration::from_secs(10),
        handle.wait_reporting(|suspended| {
            reports.push(suspended);
            let next = if suspended { &go } else { &done };
            std::fs::write(next, "").unwrap();
        }),
    )
    .await
    .expect("the command continues and exits")
    .unwrap();
    assert!(status.success());
    assert_eq!(reports, [true, false]);
}

#[tokio::test]
async fn a_group_that_suspends_itself_is_not_reported_as_suspended() {
    let mut handle = spawner()
        .spawn(&SpawnSpec::new(
            "kill -TSTP $$; echo resumed",
            std::env::temp_dir(),
        ))
        .await
        .unwrap();
    drain(handle.take_output().unwrap());
    let mut reports = Vec::new();
    let status = tokio::time::timeout(
        Duration::from_secs(10),
        handle.wait_reporting(|suspended| reports.push(suspended)),
    )
    .await
    .expect("the group is resumed and exits")
    .unwrap();
    assert!(status.success());
    assert!(!reports.contains(&true), "{reports:?}");
}

#[tokio::test]
async fn a_group_left_in_the_background_gets_the_terminal_back() {
    let command = format!(
        "{}; echo ready; read line; echo got $line",
        fixture().display()
    );
    let mut handle = spawner()
        .spawn(&SpawnSpec::new(command, std::env::temp_dir()).env("FIXTURE_TAKE_TERMINAL", "1"))
        .await
        .unwrap();
    let mut output = handle.take_output().unwrap();
    let mut seen = Vec::new();
    read_until(&mut output, &mut seen, "ready").await;
    handle.write_input(b"hi\n").await.unwrap();
    read_until(&mut output, &mut seen, "got hi").await;
    drain(output);
    assert!(handle.wait().await.unwrap().success());
}

#[tokio::test]
async fn a_group_stopped_with_sigstop_stays_stopped() {
    let dir = tempfile::tempdir().unwrap();
    let mut handle = spawner()
        .spawn(&trapping_term(&dir.path().join("terminated")))
        .await
        .unwrap();
    let mut output = handle.take_output().unwrap();
    read_until(&mut output, &mut Vec::new(), "ready").await;
    drain(output);
    handle.signal_group(Signal::SIGSTOP).unwrap();
    wait_stopped(handle.pid()).await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    wait_stopped(handle.pid()).await;
    stop(handle).await;
}

#[tokio::test]
async fn the_shim_marks_its_command_as_the_group_record_does() {
    let mut handle = spawner()
        .spawn(&SpawnSpec::new(
            "echo \"marker=$CARTE_SHIM.\"; read line",
            std::env::temp_dir(),
        ))
        .await
        .unwrap();
    let mut output = handle.take_output().unwrap();
    let mut seen = Vec::new();
    read_until(&mut output, &mut seen, ".\r\n").await;
    drain(output);
    let text = String::from_utf8_lossy(&seen).into_owned();
    let marker = text
        .split("marker=")
        .nth(1)
        .and_then(|rest| rest.split(".\r\n").next())
        .unwrap()
        .to_string();

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("groups");
    let mut record = carte::supervisor::groups::GroupRecord::new(path.clone());
    record.add(handle.pgid());
    let recorded = std::fs::read_to_string(&path).unwrap();
    stop(handle).await;
    let entry: Vec<&str> = recorded.lines().nth(1).unwrap().split(' ').collect();
    assert!(marker.starts_with(&format!("{}.", entry[2])), "{marker}");
    assert_eq!(entry[3], marker, "{recorded}");
}

#[tokio::test]
async fn sigint_is_delivered_to_the_group() {
    let mut handle = spawner().spawn(&spec()).await.unwrap();
    let mut output = handle.take_output().unwrap();
    read_until(&mut output, &mut Vec::new(), "ready").await;
    drain(output);
    handle.signal_group(Signal::SIGINT).unwrap();
    assert_eq!(handle.wait().await.unwrap().signal(), Some(libc::SIGINT));
}

#[tokio::test]
async fn shim_forwards_signals_to_the_group() {
    let dir = tempfile::tempdir().unwrap();
    let pidfile = dir.path().join("child.pid");
    let mut handle = spawner()
        .spawn(&spec().env("FIXTURE_CHILD_PIDFILE", &pidfile))
        .await
        .unwrap();
    drain(handle.take_output().unwrap());
    let child = read_pidfile(&pidfile).await;
    kill(Pid::from_raw(handle.shim_pid() as i32), Signal::SIGTERM).unwrap();
    assert_eq!(handle.wait().await.unwrap().signal(), Some(libc::SIGTERM));
    wait_dead(child).await;
}

#[tokio::test]
async fn dropping_the_handle_kills_the_whole_group() {
    let dir = tempfile::tempdir().unwrap();
    let pidfile = dir.path().join("child.pid");
    let handle = spawner()
        .spawn(
            &spec()
                .env("FIXTURE_CHILD_PIDFILE", &pidfile)
                .env("FIXTURE_IGNORE_TERM", "1"),
        )
        .await
        .unwrap();
    let (pid, shim) = (handle.pid(), handle.shim_pid());
    let child = read_pidfile(&pidfile).await;
    assert!(alive(child));
    drop(handle);
    wait_dead(child).await;
    wait_dead(pid).await;
    wait_dead(shim).await;
}

#[tokio::test]
async fn closing_the_lifeline_alone_kills_the_group() {
    let dir = tempfile::tempdir().unwrap();
    let pidfile = dir.path().join("child.pid");
    let mut handle = spawner()
        .spawn(&spec().env("FIXTURE_CHILD_PIDFILE", &pidfile))
        .await
        .unwrap();
    drain(handle.take_output().unwrap());
    let child = read_pidfile(&pidfile).await;
    handle.close_lifeline();
    let status = tokio::time::timeout(Duration::from_secs(10), handle.wait())
        .await
        .unwrap()
        .unwrap();
    assert!(!status.success());
    wait_dead(handle.pid()).await;
    wait_dead(child).await;
}

#[tokio::test]
async fn stop_reaches_groups_the_command_makes() {
    let dir = tempfile::tempdir().unwrap();
    let pidfile = dir.path().join("child.pid");
    let mut handle = spawner()
        .spawn(&spec().env("FIXTURE_GROUP_CHILD_PIDFILE", &pidfile))
        .await
        .unwrap();
    drain(handle.take_output().unwrap());
    let child = read_pidfile(&pidfile).await;
    assert!(alive(child));
    stop(handle).await;
    wait_dead(child).await;
}

#[tokio::test]
async fn groups_left_when_the_command_exits_are_stopped() {
    let dir = tempfile::tempdir().unwrap();
    let pidfile = dir.path().join("child.pid");
    let mut handle = spawner()
        .spawn(
            &spec()
                .env("FIXTURE_GROUP_CHILD_PIDFILE", &pidfile)
                .env("FIXTURE_CRASH", "0"),
        )
        .await
        .unwrap();
    let (status, _) = run_to_end(&mut handle).await;
    assert!(status.success());
    let child = read_pidfile(&pidfile).await;
    wait_dead(child).await;
}

#[tokio::test]
async fn closing_the_lifeline_reaches_groups_the_command_makes() {
    let dir = tempfile::tempdir().unwrap();
    let pidfile = dir.path().join("child.pid");
    let handle = spawner()
        .spawn(
            &spec()
                .env("FIXTURE_GROUP_CHILD_PIDFILE", &pidfile)
                .env("FIXTURE_IGNORE_TERM", "1"),
        )
        .await
        .unwrap();
    let pid = handle.pid();
    let child = read_pidfile(&pidfile).await;
    assert!(alive(child));
    drop(handle);
    wait_dead(child).await;
    wait_dead(pid).await;
}

/// On Linux the shim adopts the orphaned grandchild; macOS has no way to.
#[tokio::test]
async fn self_daemonising_child_is_stopped_on_linux() {
    let dir = tempfile::tempdir().unwrap();
    let pidfile = dir.path().join("daemon.pid");
    let handle = spawner()
        .spawn(&spec().env("FIXTURE_DAEMON_PIDFILE", &pidfile))
        .await
        .unwrap();
    let pid = handle.pid();
    let daemon = read_pidfile(&pidfile).await;
    drop(handle);
    wait_dead(pid).await;
    if cfg!(target_os = "linux") {
        wait_dead(daemon).await;
    } else {
        let escaped = alive(daemon);
        let _ = kill(Pid::from_raw(daemon as i32), Signal::SIGKILL);
        assert!(
            escaped,
            "expected the setsid grandchild to survive on macOS"
        );
    }
}

#[tokio::test]
async fn failing_command_reports_its_exit_code() {
    let mut handle = spawner()
        .spawn(&SpawnSpec::new("exit 7", "/"))
        .await
        .unwrap();
    assert_eq!(run_to_end(&mut handle).await.0.code(), Some(7));
    let mut handle = spawner()
        .spawn(&SpawnSpec::new("no-such-command-xyz", "/"))
        .await
        .unwrap();
    let (status, text) = run_to_end(&mut handle).await;
    assert_eq!(status.code(), Some(127));
    assert!(text.contains("no-such-command-xyz"), "{text:?}");
}

/// Plays the daemon for `sigkilled_daemon_takes_its_groups_down`; a no-op otherwise.
#[tokio::test]
async fn fake_daemon() {
    let Some(dir) = std::env::var_os("CARTE_TEST_FAKE_DAEMON") else {
        return;
    };
    let dir = std::path::PathBuf::from(dir);
    let mut handles = Vec::new();
    for (i, io) in [IoMode::default(), IoMode::Pipes].into_iter().enumerate() {
        let pidfile = dir.join(format!("child{i}.pid"));
        let mut handle = spawner()
            .spawn(
                &spec()
                    .io(io)
                    .env("FIXTURE_CHILD_PIDFILE", &pidfile)
                    .env("FIXTURE_IGNORE_TERM", "1"),
            )
            .await
            .unwrap();
        drain(handle.take_output().unwrap());
        std::fs::write(dir.join(format!("leader{i}.pid")), handle.pid().to_string()).unwrap();
        handles.push(handle);
    }
    std::future::pending::<()>().await;
}

#[tokio::test]
async fn sigkilled_daemon_takes_its_groups_down() {
    let dir = tempfile::tempdir().unwrap();
    fixture();
    let mut daemon = std::process::Command::new(std::env::current_exe().unwrap())
        .args(["--exact", "fake_daemon", "--nocapture"])
        .env("CARTE_TEST_FAKE_DAEMON", dir.path())
        .env("FIXTURE_LIFELINE_PID", lifeline())
        .stdout(std::process::Stdio::null())
        .spawn()
        .unwrap();
    guard(daemon.id());
    let mut pids = Vec::new();
    for i in 0..2 {
        pids.push(read_pidfile(&dir.path().join(format!("leader{i}.pid"))).await);
        pids.push(read_pidfile(&dir.path().join(format!("child{i}.pid"))).await);
    }
    assert!(pids.iter().all(|&pid| alive(pid)));
    daemon.kill().unwrap();
    daemon.wait().unwrap();
    for pid in pids {
        wait_dead(pid).await;
    }
}

/// The descriptors above stderr that `pid` has open, by number.
fn open_fds(pid: u32) -> BTreeMap<u32, String> {
    if cfg!(target_os = "linux") {
        return std::fs::read_dir(format!("/proc/{pid}/fd"))
            .map(|dir| {
                dir.flatten()
                    .filter_map(|e| {
                        let fd = e.file_name().to_string_lossy().parse::<u32>().ok()?;
                        let name = std::fs::read_link(e.path())
                            .map(|p| p.display().to_string())
                            .unwrap_or_default();
                        (fd > 2).then_some((fd, name))
                    })
                    .collect()
            })
            .unwrap_or_default();
    }
    let lsof = std::process::Command::new("lsof")
        .args(["-p", &pid.to_string(), "-F", "fn"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&lsof.stdout).into_owned();
    let mut fds = BTreeMap::new();
    let mut open = None;
    for line in text.lines() {
        if let Some(fd) = line.strip_prefix('f') {
            open = fd.parse::<u32>().ok().filter(|&fd| fd > 2);
        } else if let Some(name) = line.strip_prefix('n')
            && let Some(fd) = open
        {
            fds.insert(fd, name.to_string());
        }
    }
    fds
}

/// Starts a background `sleep 5` through a plain `sh` and returns its pid.
fn start_sleep() -> Option<u32> {
    let output = std::process::Command::new("/bin/sh")
        .args(["-c", "sleep 5 </dev/null >/dev/null 2>&1 & echo $!"])
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    String::from_utf8_lossy(&output.stdout).trim().parse().ok()
}

#[tokio::test(flavor = "multi_thread")]
async fn spawn_descriptors_dont_leak_into_other_children() {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    let first = start_sleep().unwrap();
    let inherited = open_fds(first);
    let _ = kill(Pid::from_raw(first as i32), Signal::SIGKILL);

    let done = Arc::new(AtomicBool::new(false));
    let children = std::thread::spawn({
        let done = done.clone();
        move || {
            let mut pids = Vec::new();
            while !done.load(Ordering::Relaxed) {
                pids.extend(start_sleep());
            }
            pids
        }
    });
    for io in [IoMode::default(), IoMode::Pipes].repeat(25) {
        let mut handle = spawner()
            .spawn(&SpawnSpec::new("true", "/").io(io))
            .await
            .unwrap();
        run_to_end(&mut handle).await;
    }
    done.store(true, Ordering::Relaxed);
    let pids = children.join().unwrap();
    let leaked: Vec<(u32, BTreeMap<u32, String>)> = pids
        .iter()
        .map(|&pid| {
            let mut fds = open_fds(pid);
            fds.retain(|fd, _| !inherited.contains_key(fd));
            (pid, fds)
        })
        .filter(|(_, fds)| !fds.is_empty())
        .collect();
    for &pid in &pids {
        let _ = kill(Pid::from_raw(pid as i32), Signal::SIGKILL);
    }
    assert!(!pids.is_empty());
    assert!(
        leaked.is_empty(),
        "{} of {}: {leaked:?}, besides the test's own {inherited:?}",
        leaked.len(),
        pids.len()
    );
}