shep 0.25.1

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
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
use super::*;

/// Collapsing matched rows to distinct names would widen the request:
/// `Id` is the only selector form that names a subset of one name's rows.
#[tokio::test]
async fn a_start_by_id_respawns_that_row_and_no_other() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) =
        fake_client_answering(&path, a_daemon_for(a_clustered_flock(&[]), &[])).await;

    let (code, _, _) = start_against(&client, "0").await;

    assert_eq!(code, ExitCode::Success);
    assert_eq!(
        respawns(&mut envelopes),
        vec![SelectorSpec::Id(0)],
        "one respawn, for the row the operator named"
    );
}

/// Asserts on the declared key set as well as the name, because that is
/// what a merge keys on: an empty set puts the same envelope on the wire
/// and applies nothing.
#[tokio::test]
async fn a_flockfile_load_applies_its_declared_keys_to_an_app_the_flock_has() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let flockfile = write_zam_flockfile(dir.path());
    let path = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) =
        fake_client_answering(&path, a_daemon_for(a_clustered_flock(&[0, 1, 2]), &[])).await;

    let (code, _printed, _said) = start_against(&client, flockfile.to_str().unwrap()).await;

    assert_eq!(code, ExitCode::Success);
    let mut sent = Vec::new();
    while let Ok(envelope) = envelopes.try_recv() {
        if let Request::ApplyConfig { apps, reset } = envelope.body {
            sent.push((apps, reset));
        }
    }
    assert_eq!(sent.len(), 1, "one request for the whole invocation");
    let (apps, reset) = &sent[0];
    assert_eq!(apps.len(), 1);
    assert_eq!(apps[0].config.name, "zam");
    assert!(
        apps[0].declared.contains("max_restarts"),
        "the edited key is declared: {:?}",
        apps[0].declared
    );
    assert_eq!(
        *reset,
        ResetDepth::None,
        "additive by default; --reset is something the operator types"
    );
}

/// `reset_depth` is the only place that mapping happens.
#[tokio::test]
async fn reset_modes_choose_the_apply_config_depth_on_the_wire() {
    use shep_client::testing::fake_client_answering;

    async fn sent_depth(reset: Option<ResetMode>) -> ResetDepth {
        let dir = tempfile::tempdir().unwrap();
        let flockfile = write_zam_flockfile(dir.path());
        let path = shep_client::testing::control_address(dir.path());
        let (client, mut envelopes) =
            fake_client_answering(&path, a_daemon_for(a_clustered_flock(&[0, 1, 2]), &[])).await;
        let mut args = start_args(flockfile.to_str().unwrap());
        args.reset = reset;
        let (code, _printed, _said) = start_against_with_args(&client, &args).await;
        assert_eq!(code, ExitCode::Success);
        let mut sent = Vec::new();
        while let Ok(envelope) = envelopes.try_recv() {
            if let Request::ApplyConfig { reset, .. } = envelope.body {
                sent.push(reset);
            }
        }
        assert_eq!(sent.len(), 1, "one request for the whole invocation");
        sent[0]
    }

    assert_eq!(sent_depth(None).await, ResetDepth::None);
    assert_eq!(sent_depth(Some(ResetMode::File)).await, ResetDepth::File);
    assert_eq!(
        sent_depth(Some(ResetMode::Policy)).await,
        ResetDepth::Policy
    );
    assert_eq!(sent_depth(Some(ResetMode::Env)).await, ResetDepth::Env);
    assert_eq!(sent_depth(Some(ResetMode::All)).await, ResetDepth::All);
}

/// There is no file to reset to, so the flag is meaningless.
#[tokio::test]
async fn a_reset_flag_on_a_name_target_is_refused() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) =
        fake_client_answering(&path, a_daemon_for(a_clustered_flock(&[0, 1, 2]), &[])).await;

    let mut args = start_args("zam");
    args.reset = Some(ResetMode::Env);
    let (code, printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Usage);
    assert!(printed.is_empty(), "a refusal prints no data envelope");
    assert!(
        said.contains("--reset=env") && said.contains("zam"),
        "the refusal must echo the mode the operator actually typed, \
             not a bare --reset that is now its own usage error: {said}"
    );
}

/// The command line is not a template, so the flag would otherwise exit
/// 0 having reset nothing.
#[tokio::test]
async fn a_reset_flag_on_a_bare_script_target_is_refused() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) =
        fake_client_answering(&path, a_daemon_for(a_clustered_flock(&[0, 1, 2]), &[])).await;

    let mut args = start_args(script.to_str().unwrap());
    args.reset = Some(ResetMode::All);
    let (code, printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Usage);
    assert!(printed.is_empty(), "a refusal prints no data envelope");
    assert!(
        said.contains("--reset=all") && said.contains("zam"),
        "the refusal must echo the mode the operator actually typed, \
             not a bare --reset that is now its own usage error: {said}"
    );
    assert!(
        applies(&mut envelopes).is_empty(),
        "a refused reset sends no load"
    );
}

/// The command line supplied every value, including a `cwd` of wherever
/// the operator stood, so applying it would move a running app's
/// directory.
#[tokio::test]
async fn an_assignment_is_recorded_as_an_operator_override() {
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();

    let sock = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) = fake_client_answering(&sock, |request: &Request| match request {
        Request::ListFlock => Response::Flock(Vec::new()),
        Request::Start { apps } => Response::Started(
            apps.iter()
                .map(|app| ProcessInfo::builder(0, app.name.as_str(), ProcStatus::Online).build())
                .collect(),
        ),
        Request::SetSheepEnv { name, key, .. } => Response::SheepEnvSet {
            name: name.clone(),
            key: key.clone(),
        },
        _ => Response::Pong,
    })
    .await;

    let mut args = start_args("KOJI_TOKEN=s3cret");
    args.targets.push(script.to_string_lossy().into_owned());
    let (code, _printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Success, "{said}");
    let mut recorded = Vec::new();
    while let Ok(envelope) = envelopes.try_recv() {
        if let Request::SetSheepEnv { name, key, value } = envelope.body {
            recorded.push((name, key, value.map(|v| v.as_str().to_string())));
        }
    }
    assert_eq!(
        recorded,
        vec![(
            "zam".to_string(),
            "KOJI_TOKEN".to_string(),
            Some("s3cret".to_string())
        )],
        "without the override record a later Flockfile load overwrites the value"
    );
}

#[tokio::test]
async fn an_assignment_reaches_the_env_of_the_sheep_it_registers() {
    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();

    let sock = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) = fake_client_capturing_envelopes(&sock).await;
    let mut args = start_args("KOJI_TOKEN=s3cret");
    args.targets.push(script.to_string_lossy().into_owned());
    let _ = start_against_with_args(&client, &args).await;

    let apps = start_apps(next_start(&mut envelopes).await);
    assert_eq!(apps.len(), 1);
    assert_eq!(
        apps[0].env.get("KOJI_TOKEN").map(String::as_str),
        Some("s3cret"),
        "the first spawn must already carry the value"
    );
}

/// Each Flockfile's own value must reach the wire without the flag, and
/// the flag must win over `stamped`'s `true`.
#[tokio::test]
async fn no_log_timestamps_reaches_the_sheep_a_script_or_a_flockfile_registers() {
    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let flockfile = |name: &str, value: bool| {
        let path = dir.path().join(format!("{name}.toml"));
        let app = "[[app]]\nname = \"koji\"\nscript = \"/bin/sleep\"\n";
        std::fs::write(&path, format!("{app}log_timestamps = {value}\n")).unwrap();
        path
    };
    let (stamped, unstamped) = (flockfile("stamped", true), flockfile("unstamped", false));

    for (target, flag, want) in [
        (&script, false, true),
        (&script, true, false),
        (&stamped, false, true),
        (&stamped, true, false),
        (&unstamped, false, false),
    ] {
        let home = tempfile::tempdir().unwrap();
        let sock = shep_client::testing::control_address(home.path());
        let (client, mut envelopes) = fake_client_capturing_envelopes(&sock).await;
        // The target itself, not an assignment followed by a pushed target.
        let mut args = start_args(&target.to_string_lossy());
        args.no_log_timestamps = flag;
        let _ = start_against_with_args(&client, &args).await;

        let apps = start_apps(next_start(&mut envelopes).await);
        assert_eq!(apps.len(), 1, "{target:?} registers one app");
        assert_eq!(
            apps[0].log_timestamps, want,
            "{target:?} with the flag {flag}"
        );
    }
}

/// A sheep the flock already has is merged through `apply_declared`, which
/// sends only the keys the load declared, so a flag that declares nothing
/// has to travel as an override write instead.
///
/// The order is the assertion: `log_timestamps` is a `NeedsRespawn` field,
/// so it parks, and the resume directly below is the spawn that promotes
/// it.
#[tokio::test]
async fn no_log_timestamps_on_an_existing_sheep_sends_the_field_before_the_resume() {
    use shep_client::testing::fake_client_answering;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let flock = vec![ProcessInfo::builder(0, "zam", ProcStatus::Stopped).build()];
    let (client, mut envelopes) =
        fake_client_answering(&sock, move |request: &Request| match request {
            Request::ListFlock => Response::Flock(flock.clone()),
            Request::SetSheepField { name, key, .. } => Response::SheepFieldSet {
                name: name.clone(),
                key: key.clone(),
                pending: true,
                warning: None,
            },
            Request::Restart { .. } => Response::Restarted {
                accepted: vec![ProcessInfo::builder(0, "zam", ProcStatus::Online).build()],
                refused: Vec::new(),
            },
            _ => Response::Pong,
        })
        .await;

    let mut args = start_args(script.to_str().unwrap());
    args.no_log_timestamps = true;
    let (code, _printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Success, "{said}");
    let mut order = Vec::new();
    while let Ok(envelope) = envelopes.try_recv() {
        match envelope.body {
            Request::SetSheepField { name, key, value } => {
                assert_eq!(
                    name, "zam",
                    "the write names the sheep the flock already has"
                );
                assert_eq!(key, "log_timestamps");
                assert_eq!(
                    value,
                    serde_json::json!(false),
                    "the flag is the Flockfile's `log_timestamps = false`"
                );
                order.push("field".to_string());
            }
            Request::Restart { .. } => order.push("restart".to_string()),
            _ => {}
        }
    }
    assert_eq!(
        order,
        ["field", "restart"],
        "the parked value must be written before the spawn that promotes it"
    );
}

/// The failure case for the one above: without the flag the sheep's own
/// `log_timestamps` is nobody's to write.
#[tokio::test]
async fn an_existing_sheep_without_the_flag_gets_no_field_write() {
    use shep_client::testing::fake_client_answering;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let flock = vec![ProcessInfo::builder(0, "zam", ProcStatus::Stopped).build()];
    let (client, mut envelopes) =
        fake_client_answering(&sock, move |request: &Request| match request {
            Request::ListFlock => Response::Flock(flock.clone()),
            Request::Restart { .. } => Response::Restarted {
                accepted: vec![ProcessInfo::builder(0, "zam", ProcStatus::Online).build()],
                refused: Vec::new(),
            },
            _ => Response::Pong,
        })
        .await;

    let (code, _printed, said) = start_against(&client, script.to_str().unwrap()).await;

    assert_eq!(code, ExitCode::Success, "{said}");
    let fields: Vec<String> = sent(&mut envelopes)
        .into_iter()
        .filter_map(|body| match body {
            Request::SetSheepField { key, .. } => Some(key),
            _ => None,
        })
        .collect();
    assert!(
        fields.is_empty(),
        "a flag the operator did not type writes nothing: {fields:?}"
    );
}

/// The operator asked for stamps off, so a shepherd that will not write
/// them is a failed verb rather than a notice beside a flock that kept them.
#[tokio::test]
async fn a_refused_field_write_fails_naming_the_sheep() {
    use shep_client::testing::fake_client_answering_refusals;
    use shep_core::protocol::RpcError;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let flock = vec![ProcessInfo::builder(0, "zam", ProcStatus::Stopped).build()];
    let (client, mut envelopes) =
        fake_client_answering_refusals(&sock, move |request: &Request| match request {
            Request::ListFlock => Ok(Response::Flock(flock.clone())),
            Request::SetSheepField { .. } => Err(RpcError {
                code: RpcErrorCode::InvalidConfig,
                message: "no config field named log_timestamps".to_string(),
                daemon_version: None,
            }),
            _ => Ok(Response::Pong),
        })
        .await;

    let mut args = start_args(script.to_str().unwrap());
    args.no_log_timestamps = true;
    let (code, printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(
        code,
        ExitCode::InvalidConfig,
        "a refused config write is the code a refused field in a load already takes: {said}"
    );
    assert!(printed.is_empty(), "a failed verb leaves stdout empty");
    assert!(said.contains("zam"), "the failure names the sheep: {said}");
    assert!(
        said.contains("log_timestamps"),
        "and the value it could not set: {said}"
    );
    assert!(
        respawns(&mut envelopes).is_empty(),
        "the sheep is not brought back up stamped"
    );
}

/// The shepherd parks a `NeedsRespawn` field and answers with the `pending`
/// bit, the bit `SetSheepField` carries it for. A load that says nothing
/// about a parked field reports a flock whose stamp is still on.
#[tokio::test]
async fn a_parked_stamp_write_says_what_promotes_it() {
    use shep_client::testing::fake_client_answering;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let flock = vec![ProcessInfo::builder(0, "zam", ProcStatus::Online).build()];
    let (client, mut envelopes) =
        fake_client_answering(&sock, move |request: &Request| match request {
            Request::ListFlock => Response::Flock(flock.clone()),
            Request::SetSheepField { name, key, .. } => Response::SheepFieldSet {
                name: name.clone(),
                key: key.clone(),
                pending: true,
                warning: None,
            },
            _ => Response::Pong,
        })
        .await;

    let mut args = start_args(script.to_str().unwrap());
    args.no_log_timestamps = true;
    let (code, printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Success, "{said}");
    assert!(
        said.contains(
            "notice[start]: zam: log_timestamps waiting on the next spawn \
             (`shep reload zam` promotes them)"
        ),
        "the parked write is reported the way a parked declared key is: {said}"
    );
    assert!(
        !printed.contains("log_timestamps"),
        "a notice is not the answer the verb was asked for, so it stays off \
         stdout: {printed}"
    );
    assert!(
        respawns(&mut envelopes).is_empty(),
        "an online sheep is left running, which is what makes the value parked"
    );
}

/// `warning` is advisory beside a write that landed. The shepherd answers one
/// only for `cwd`, `script`, `out_file` and `err_file`, so this pins the
/// passthrough rather than a case `log_timestamps` produces.
#[tokio::test]
async fn a_field_write_warning_reaches_the_operator_as_the_shepherds_sentence() {
    use shep_client::testing::fake_client_answering;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let flock = vec![ProcessInfo::builder(0, "zam", ProcStatus::Stopped).build()];
    let advisory = "cwd /tmp/gone does not exist";
    let advisory_for_test = advisory.to_string();
    let (client, _envelopes) =
        fake_client_answering(&sock, move |request: &Request| match request {
            Request::ListFlock => Response::Flock(flock.clone()),
            Request::SetSheepField { name, key, .. } => Response::SheepFieldSet {
                name: name.clone(),
                key: key.clone(),
                pending: false,
                warning: Some(advisory_for_test.clone()),
            },
            Request::Restart { .. } => Response::Restarted {
                accepted: vec![ProcessInfo::builder(0, "zam", ProcStatus::Online).build()],
                refused: Vec::new(),
            },
            _ => Response::Pong,
        })
        .await;

    let mut args = start_args(script.to_str().unwrap());
    args.no_log_timestamps = true;
    let (code, _printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Success, "{said}");
    assert!(
        said.contains(&format!("notice[warning]: {advisory}")),
        "the write landed, so this is the shepherd's sentence about the disk \
         and not a refusal: {said}"
    );
    assert!(
        !said.contains("waiting on the next spawn"),
        "the shepherd said the value is in force, so no parked clause belongs \
         here: {said}"
    );
}

#[tokio::test]
async fn an_assignment_on_an_existing_sheep_is_recorded_before_it_resumes() {
    use shep_client::testing::fake_client_answering;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let flock = vec![ProcessInfo::builder(0, "zam", ProcStatus::Stopped).build()];
    let (client, mut envelopes) =
        fake_client_answering(&sock, move |request: &Request| match request {
            Request::ListFlock => Response::Flock(flock.clone()),
            Request::SetSheepEnv { name, key, .. } => Response::SheepEnvSet {
                name: name.clone(),
                key: key.clone(),
            },
            Request::Restart { .. } => Response::Restarted {
                accepted: vec![ProcessInfo::builder(0, "zam", ProcStatus::Online).build()],
                refused: Vec::new(),
            },
            _ => Response::Pong,
        })
        .await;

    let mut args = start_args("A=1");
    args.targets.push("zam".to_string());
    let (code, _printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Success, "{said}");
    let mut order = Vec::new();
    while let Ok(envelope) = envelopes.try_recv() {
        match envelope.body {
            Request::SetSheepEnv { key, .. } => order.push(format!("set {key}")),
            Request::Restart { .. } => order.push("restart".to_string()),
            _ => {}
        }
    }
    assert_eq!(
        order,
        ["set A", "restart"],
        "the value must be recorded before the sheep comes back up"
    );
}

#[tokio::test]
async fn an_assignment_on_a_target_matching_several_sheep_is_refused() {
    use shep_client::testing::fake_client_answering;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let flock = vec![
        ProcessInfo::builder(0, "web", ProcStatus::Online).build(),
        ProcessInfo::builder(1, "api", ProcStatus::Online).build(),
    ];
    let (client, mut envelopes) = fake_client_answering(&sock, a_daemon_for(flock, &[])).await;

    let mut args = start_args("A=1");
    args.targets.push("all".to_string());
    let (code, printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Usage);
    assert!(printed.is_empty(), "a refusal prints no data envelope");
    assert!(
        said.contains("one sheep"),
        "the refusal must say an environment belongs to one sheep: {said}"
    );
    assert!(
        respawns(&mut envelopes).is_empty(),
        "a refused assignment restarts nothing"
    );
}

#[tokio::test]
async fn an_assignment_reaches_the_env_of_a_sheep_add_registers() {
    use shep_client::testing::fake_client_answering;
    use shep_core::status::ProcStatus;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) = fake_client_answering(&sock, |request: &Request| match request {
        Request::ListFlock => Response::Flock(Vec::new()),
        Request::Add { apps } => Response::Added(
            apps.iter()
                .map(|app| ProcessInfo::builder(0, app.name.as_str(), ProcStatus::Stopped).build())
                .collect(),
        ),
        Request::SetSheepEnv { name, key, .. } => Response::SheepEnvSet {
            name: name.clone(),
            key: key.clone(),
        },
        _ => Response::Pong,
    })
    .await;

    let mut args = start_args("KOJI_TOKEN=s3cret");
    args.targets.push(script.to_string_lossy().into_owned());
    let mut out = Vec::new();
    let mut err = Vec::new();
    let code = {
        let mut streams = Streams::bare(&mut out, &mut err, Format::Table);
        add(&client, &mut streams, &args, None, &BTreeMap::new()).await
    };
    assert_eq!(code, ExitCode::Success, "{}", String::from_utf8_lossy(&err));

    let mut registered = None;
    let mut recorded = Vec::new();
    while let Ok(envelope) = envelopes.try_recv() {
        match envelope.body {
            Request::Add { apps } => {
                registered = apps
                    .first()
                    .and_then(|app| app.env.get("KOJI_TOKEN").cloned());
            }
            Request::SetSheepEnv { key, .. } => recorded.push(key),
            _ => {}
        }
    }
    assert_eq!(
        registered.as_deref(),
        Some("s3cret"),
        "add registers the value it was given"
    );
    assert_eq!(
        recorded,
        ["KOJI_TOKEN"],
        "and records it as an override, exactly as start does"
    );
}

#[test]
fn a_target_that_looks_like_an_assignment_says_why_it_is_not_one() {
    let said = TargetError::Unresolvable {
        target: "1A=1".to_string(),
    }
    .to_string();

    assert!(
        said.contains("`1A`"),
        "the refusal names the bad name: {said}"
    );
    assert!(
        said.contains("letter"),
        "and says what a name may hold: {said}"
    );
}

#[test]
fn a_path_holding_an_equals_sign_gets_no_assignment_note() {
    let said = TargetError::Unresolvable {
        target: "./A=1".to_string(),
    }
    .to_string();

    assert!(
        !said.contains("letter"),
        "a path was never a candidate assignment: {said}"
    );
}

#[tokio::test]
async fn a_quoted_assignment_and_target_says_to_drop_the_quotes() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&sock, a_daemon_for(Vec::new(), &[])).await;

    let args = start_args("ABC=xyz /tmp/x/koji");
    let (code, printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Usage);
    assert!(printed.is_empty(), "a refusal prints no data envelope");
    assert!(
        said.contains("drop the quotes"),
        "one quoted word is the shape a shell never produces: {said}"
    );
}

#[tokio::test]
async fn an_assignment_with_no_target_at_all_is_refused() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let (client, _envelopes) = fake_client_answering(&sock, a_daemon_for(Vec::new(), &[])).await;

    let args = start_args("A=1");
    let (code, _printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Usage);
    assert!(
        said.contains("needs a target"),
        "an environment with nothing to set it on: {said}"
    );
}

#[tokio::test]
async fn an_assignment_on_a_flockfile_is_refused() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let flockfile = dir.path().join("Flockfile.toml");
    std::fs::write(
        &flockfile,
        "[[app]]\nname = \"web\"\nscript = \"/bin/sleep\"\n",
    )
    .unwrap();
    let sock = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) = fake_client_answering(&sock, a_daemon_for(Vec::new(), &[])).await;

    let mut args = start_args("A=1");
    args.targets.push(flockfile.to_string_lossy().into_owned());
    let (code, printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Usage);
    assert!(printed.is_empty(), "a refusal prints no data envelope");
    assert!(
        said.contains("Flockfile"),
        "the refusal must say a file may declare several sheep: {said}"
    );
    assert!(
        applies(&mut envelopes).is_empty(),
        "a refused assignment loads nothing"
    );
}

#[tokio::test]
async fn an_assignment_with_more_than_one_target_is_refused() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) =
        fake_client_answering(&path, a_daemon_for(a_clustered_flock(&[0, 1, 2]), &[])).await;

    let mut args = start_args("A=1");
    args.targets.push(script.to_string_lossy().into_owned());
    args.targets.push(script.to_string_lossy().into_owned());
    let (code, printed, said) = start_against_with_args(&client, &args).await;

    assert_eq!(code, ExitCode::Usage);
    assert!(printed.is_empty(), "a refusal prints no data envelope");
    assert!(
        said.contains("one target"),
        "the refusal must say an environment belongs to one sheep: {said}"
    );
    assert!(
        applies(&mut envelopes).is_empty(),
        "a refused assignment loads nothing"
    );
}

#[tokio::test]
async fn a_bare_script_target_applies_nothing() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let script = dir.path().join("zam");
    std::fs::write(&script, "#!/bin/sh\nsleep 1\n").unwrap();
    let path = shep_client::testing::control_address(dir.path());
    let (client, mut envelopes) =
        fake_client_answering(&path, a_daemon_for(a_clustered_flock(&[0, 1, 2]), &[])).await;

    let (code, _printed, _said) = start_against(&client, script.to_str().unwrap()).await;

    assert_eq!(code, ExitCode::Success);
    assert!(
        applies(&mut envelopes).is_empty(),
        "a script path declares nothing, so there is nothing to apply"
    );
}

/// A list of names nobody can act on is a report nobody can use.
#[tokio::test]
async fn a_load_names_the_verb_that_promotes_what_is_pending() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let flockfile = write_zam_flockfile(dir.path());
    let path = shep_client::testing::control_address(dir.path());
    let flock = a_clustered_flock(&[0, 1, 2]);
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::ListFlock => Response::Flock(flock.clone()),
        Request::ApplyConfig { .. } => Response::Applied(vec![SheepApplied::new(
            "zam",
            vec!["max_restarts".to_string()],
            vec!["env".to_string()],
            None,
        )]),
        _ => Response::Pong,
    })
    .await;

    let (code, _printed, said) = start_against(&client, flockfile.to_str().unwrap()).await;

    assert_eq!(code, ExitCode::Success);
    assert!(
        said.contains("applied max_restarts"),
        "what landed is named: {said}"
    );
    assert!(
        said.contains("shep reload zam"),
        "and what promotes the rest: {said}"
    );
}

/// Both apps are in one reply: one refusal among successes still fails
/// the verb, and the app that did apply is still reported.
#[tokio::test]
async fn a_load_that_refused_an_app_exits_non_zero_and_still_reports_the_rest() {
    use shep_client::testing::fake_client_answering;

    let dir = tempfile::tempdir().unwrap();
    let flockfile = write_zam_flockfile(dir.path());
    let path = shep_client::testing::control_address(dir.path());
    let flock = a_clustered_flock(&[0, 1, 2]);
    let (client, _envelopes) = fake_client_answering(&path, move |request| match request {
        Request::ListFlock => Response::Flock(flock.clone()),
        Request::ApplyConfig { .. } => Response::Applied(vec![
            SheepApplied::new("zam", vec!["max_restarts".to_string()], Vec::new(), None),
            SheepApplied::new(
                "api",
                Vec::new(),
                Vec::new(),
                Some("instances: this load never reshapes a flock".to_string()),
            ),
        ]),
        _ => Response::Pong,
    })
    .await;

    let (code, printed, said) = start_against(&client, flockfile.to_str().unwrap()).await;

    assert_eq!(
        code,
        ExitCode::InvalidConfig,
        "a refused load is a failed load: {said}"
    );
    assert!(
        said.contains("never reshapes a flock"),
        "the refusal reaches the operator: {said}"
    );
    assert!(
        said.contains("applied max_restarts"),
        "and so does what did land, beside it: {said}"
    );
    assert!(
        printed.is_empty(),
        "a failed verb leaves stdout empty, so `--format json` never \
             carries a data envelope beside an error one: {printed}"
    );
}