shep 0.24.2

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
//! A dog pane's `shep.pane` pull: the manifest read that decides whether to
//! ask, and how the answer, or the reason there is none, lands on the pane.

use super::*;

impl App {
    /// `Msg::DogDeclaresPane`'s arm: the manifest has been read, and a dog
    /// that declares a pane is asked for it.
    ///
    /// Dropped when the dog's config pane is not the one open, or is a later
    /// opening than the one the read was raised for. A pull already waiting
    /// is not sent a second time.
    pub(super) fn on_dog_declares_pane(
        &mut self,
        name: &str,
        opening: u64,
        declared: Option<DeclaredPane>,
    ) -> Effect {
        let Some(declared) = declared else {
            return Effect::None;
        };
        let now = self.now;
        let Some(pane) = self.dog_pane_of(name, opening) else {
            return Effect::None;
        };
        pane.declare_pane(declared);
        if pane
            .status_mut()
            .is_some_and(|status| status.begin_pull(now))
        {
            Effect::Send(Sent::DogPane {
                name: name.to_owned(),
                opening,
            })
        } else {
            Effect::None
        }
    }

    /// One `shep.pane` pull's reply, read for the dog's own pane.
    pub(super) fn on_dog_pane_pulled(
        &mut self,
        name: &str,
        opening: u64,
        result: Result<Response, RequestError>,
    ) -> Effect {
        self.land_dog_pane(name, opening, read_pulled_pane(name, result))
    }

    /// Lands a pull's answer on the dog's pane, dropped when the operator has
    /// left that pane, or has opened it again since the pull was sent.
    ///
    /// Sends the pull an action queued behind this one, if there is one.
    pub(super) fn land_dog_pane(
        &mut self,
        name: &str,
        opening: u64,
        answer: Result<Pane, String>,
    ) -> Effect {
        let again = self
            .dog_pane_of(name, opening)
            .and_then(ConfigPane::status_mut)
            .is_some_and(|status| status.land(answer));
        if again {
            Effect::Send(Sent::DogPane {
                name: name.to_owned(),
                opening,
            })
        } else {
            Effect::None
        }
    }

    /// The open config pane, when it is dog `name`'s and the `opening` given
    /// is the latest.
    pub(super) fn dog_pane_of(&mut self, name: &str, opening: u64) -> Option<&mut ConfigPane> {
        if opening != self.dog_opening {
            return None;
        }
        self.config_pane_mut().filter(
            |pane| matches!(pane.target(), PaneTarget::Dog { name: open, .. } if open == name),
        )
    }
}

/// What a `shep.pane` pull came back with, as a pane or as the one line the
/// operator reads in its place.
///
/// Every line is run through [`sanitise`](crate::terminal_safe::sanitise): a
/// dog's own words are quoted in one, and nothing it writes may drive the
/// terminal or break the line.
fn read_pulled_pane(name: &str, result: Result<Response, RequestError>) -> Result<Pane, String> {
    replied_body(name, result)
        .and_then(|body| Pane::read(&body))
        .map_err(|line| crate::terminal_safe::sanitise(&line).0)
}

/// The body dog `name` replied to a trigger with, or the one line that says
/// why there is none.
pub(super) fn replied_body(
    name: &str,
    result: Result<Response, RequestError>,
) -> Result<String, String> {
    match result {
        Ok(Response::Triggered(rows)) => {
            let row = rows
                .into_iter()
                .find(|row| row.name == name)
                .ok_or_else(|| format!("{name} gave no answer"))?;
            match row.outcome {
                ActionOutcome::Replied { body } => Ok(body),
                ActionOutcome::TimedOut => Err(format!("{name} did not answer in time")),
                ActionOutcome::NoChannel => Err(format!("{name} has no shepherd channel")),
                ActionOutcome::DogNoChannel => {
                    Err(format!("{name} was started without a shepherd channel"))
                }
                ActionOutcome::Skipped => {
                    Err(format!("{name} is being replaced, so it was not asked"))
                }
                _unknown => Err(format!("{name} answered in a way this shep does not know")),
            }
        }
        other => Err(failed_reply(other)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lookout::app::testing::*;
    use crate::lookout::pane::PaneState;
    use shep_core::protocol::{ActionOutcome, ActionReply};

    /// The first opening of a pane, which every test here opens once.
    const OPENING: u64 = 1;

    /// The row's own dog, adopted from `/opt/paddock`, with the gate open.
    fn adopted_dog_row() -> ProcessInfo {
        ProcessInfo::builder(92, "paddock", ProcStatus::Online)
            .pid(Some(92_000))
            .dog(Some(DogSource::Adopted {
                grants: None,
                path: "/opt/paddock".to_string(),
                channel: true,
                events: Vec::new(),
            }))
            .build()
    }

    /// `dog`'s config pane opened the way the event loop opens it: `e`, the
    /// schema, then the section. Returns the app and what the section's reply
    /// raised.
    #[track_caller]
    fn open_dog_pane(dog: ProcessInfo) -> (App, Effect) {
        let name = dog.name.clone();
        let mut app = fixtures::app_with(vec![dog], fixtures::plain());
        app.set_control_for_tests(Control::Allowed);
        let Effect::LoadDogPane { adopted_path, .. } = app.update(Msg::Key(KeyPress::Edit)) else {
            panic!("`e` on a dog row probes its schema");
        };
        app.update(Msg::DogPane {
            name: name.clone(),
            adopted_path,
            env_keys: Vec::new(),
            result: Ok(serde_json::json!({
                "type": "object",
                "properties": { "ratio": { "type": "number" } },
            })),
        });
        let effect = app.update(Msg::Replied {
            sent: Sent::DogSection { name },
            result: Ok(Response::DogSection {
                toml: "ratio = 1.5\n".to_string().into(),
            }),
        });
        (app, effect)
    }

    fn declared() -> DeclaredPane {
        DeclaredPane {
            actions: vec!["revoke".to_string()],
            events: vec!["lease.changed".to_string()],
        }
    }

    /// An adopted dog's pane with its pull out, ready for an answer.
    #[track_caller]
    fn pulling_paddock() -> App {
        let (mut app, _) = open_dog_pane(adopted_dog_row());
        let effect = app.update(Msg::DogDeclaresPane {
            name: "paddock".to_string(),
            opening: OPENING,
            declared: Some(declared()),
        });
        assert_eq!(effect, Effect::Send(pull_of("paddock")));
        app
    }

    fn pull_of(name: &str) -> Sent {
        Sent::DogPane {
            name: name.to_string(),
            opening: OPENING,
        }
    }

    fn triggered(name: &str, outcome: ActionOutcome) -> Result<Response, RequestError> {
        Ok(Response::Triggered(vec![ActionReply {
            id: 92,
            name: name.to_string(),
            outcome,
        }]))
    }

    fn answer(app: &mut App, result: Result<Response, RequestError>) {
        let effect = app.update(Msg::Replied {
            sent: pull_of("paddock"),
            result,
        });
        assert_eq!(effect, Effect::None, "an answer raises nothing");
    }

    #[track_caller]
    fn state_of(app: &App) -> PaneState {
        app.config_pane()
            .and_then(ConfigPane::status)
            .expect("the dog declared a pane")
            .state()
            .clone()
    }

    fn a_pane() -> Pane {
        Pane::new().fields("host", [("VRAM", "20 / 24 GiB")])
    }

    #[test]
    fn opening_an_adopted_dogs_pane_reads_its_manifest() {
        let (app, effect) = open_dog_pane(adopted_dog_row());
        assert_eq!(
            effect,
            Effect::ReadDogPane {
                name: "paddock".to_string(),
                opening: OPENING,
                adopted_path: PathBuf::from("/opt/paddock"),
            }
        );
        assert!(
            app.config_pane()
                .is_some_and(|pane| pane.status().is_none()),
            "nothing is declared until the manifest says so"
        );
    }

    #[test]
    fn opening_a_built_in_dogs_pane_reads_no_manifest() {
        let bark = ProcessInfo::builder(91, "bark", ProcStatus::Online)
            .dog(Some(DogSource::BuiltIn {
                grants: None,
                events: Vec::new(),
            }))
            .build();
        let (app, effect) = open_dog_pane(bark);
        assert_eq!(effect, Effect::None);
        assert!(app.config_pane().is_some(), "and the pane opens as it did");
    }

    #[test]
    fn a_pane_over_a_host_reads_no_manifest() {
        let mut app = fixtures::app_with(vec![adopted_dog_row()], fixtures::plain());
        app.set_control_for_tests(Control::Allowed);
        app.update(Msg::DogPane {
            name: "paddock".to_string(),
            adopted_path: Some(PathBuf::from("/opt/paddock")),
            env_keys: Vec::new(),
            result: Ok(serde_json::json!({ "type": "object", "properties": {} })),
        });
        app.set_remote_host("build-01");
        let effect = app.update(Msg::Replied {
            sent: Sent::DogSection {
                name: "paddock".to_string(),
            },
            result: Ok(Response::DogSection {
                toml: String::new().into(),
            }),
        });
        assert_eq!(effect, Effect::None, "the cache is this machine's");
    }

    /// The manifest was read when the pane opened, and a re-read of the
    /// section is not an open.
    #[test]
    fn a_re_read_reads_no_manifest_and_keeps_what_was_pulled() {
        let mut app = pulling_paddock();
        answer(
            &mut app,
            triggered(
                "paddock",
                ActionOutcome::Replied {
                    body: a_pane().body().unwrap(),
                },
            ),
        );
        let effect = app.update(Msg::Replied {
            sent: Sent::DogSection {
                name: "paddock".to_string(),
            },
            result: Ok(Response::DogSection {
                toml: "ratio = 2.0\n".to_string().into(),
            }),
        });
        assert_eq!(effect, Effect::None);
        assert_eq!(state_of(&app), PaneState::Ready(a_pane()));
        assert_eq!(
            app.config_pane()
                .and_then(ConfigPane::status)
                .map(DogStatus::declared),
            Some(&declared())
        );
    }

    #[test]
    fn a_dog_that_declares_a_pane_is_asked_for_it_and_its_actions_and_events_are_kept() {
        let (mut app, _) = open_dog_pane(adopted_dog_row());
        let effect = app.update(Msg::DogDeclaresPane {
            name: "paddock".to_string(),
            opening: OPENING,
            declared: Some(declared()),
        });
        assert_eq!(effect, Effect::Send(pull_of("paddock")));
        let status = app
            .config_pane()
            .and_then(ConfigPane::status)
            .expect("declared");
        assert_eq!(status.declared(), &declared());
        assert_eq!(status.state(), &PaneState::Waiting);
    }

    #[test]
    fn a_dog_that_declares_none_is_asked_for_nothing() {
        let (mut app, _) = open_dog_pane(adopted_dog_row());
        let effect = app.update(Msg::DogDeclaresPane {
            name: "paddock".to_string(),
            opening: OPENING,
            declared: None,
        });
        assert_eq!(effect, Effect::None);
        assert!(
            app.config_pane()
                .is_some_and(|pane| pane.status().is_none())
        );
    }

    #[test]
    fn a_second_pull_while_one_is_waiting_is_not_sent() {
        let mut app = pulling_paddock();
        let again = app.update(Msg::DogDeclaresPane {
            name: "paddock".to_string(),
            opening: OPENING,
            declared: Some(declared()),
        });
        assert_eq!(again, Effect::None);
        assert_eq!(state_of(&app), PaneState::Waiting);
    }

    #[test]
    fn a_pull_answered_is_ready_with_the_pane_read() {
        let mut app = pulling_paddock();
        answer(
            &mut app,
            triggered(
                "paddock",
                ActionOutcome::Replied {
                    body: a_pane().body().unwrap(),
                },
            ),
        );
        assert_eq!(state_of(&app), PaneState::Ready(a_pane()));
    }

    #[test]
    fn a_pull_that_comes_to_nothing_says_why_in_one_line() {
        let cases = [
            (
                triggered("paddock", ActionOutcome::TimedOut),
                "paddock did not answer in time",
            ),
            (
                triggered("paddock", ActionOutcome::NoChannel),
                "paddock has no shepherd channel",
            ),
            (
                triggered("paddock", ActionOutcome::DogNoChannel),
                "paddock was started without a shepherd channel",
            ),
            (
                triggered("paddock", ActionOutcome::Skipped),
                "paddock is being replaced, so it was not asked",
            ),
            (
                Err(RequestError::Timeout {
                    after: Duration::from_secs(60),
                }),
                "no reply within 60s",
            ),
        ];
        for (result, reason) in cases {
            let mut app = pulling_paddock();
            answer(&mut app, result);
            assert_eq!(state_of(&app), PaneState::Unavailable(reason.to_string()));
        }
    }

    /// The dog's own words are quoted at `shep.validate`'s cap, and nothing it
    /// writes breaks the line.
    #[test]
    fn an_unreadable_answer_is_quoted_at_the_cap_on_one_line() {
        let mut app = pulling_paddock();
        let body = format!("{}\n\u{1b}[2J{}", "x".repeat(150), "y".repeat(300));
        answer(
            &mut app,
            triggered("paddock", ActionOutcome::Replied { body }),
        );
        let PaneState::Unavailable(reason) = state_of(&app) else {
            panic!("an unreadable answer holds no pane");
        };
        assert!(
            reason.starts_with("the dog answered with something shep cannot read: xxx"),
            "{reason}"
        );
        assert!(reason.ends_with("..."), "{reason}");
        assert!(!reason.contains(['\n', '\u{1b}']), "{reason:?}");
        assert!(reason.len() < 300, "{} bytes", reason.len());
    }

    /// One slow answer does not blank the tab.
    #[test]
    fn a_pull_that_fails_keeps_the_last_good_pane_and_the_reason() {
        let mut app = pulling_paddock();
        answer(
            &mut app,
            triggered(
                "paddock",
                ActionOutcome::Replied {
                    body: a_pane().body().unwrap(),
                },
            ),
        );
        let status = |app: &App| {
            app.config_pane()
                .and_then(ConfigPane::status)
                .cloned()
                .unwrap()
        };
        assert_eq!(status(&app).failed(), None);

        answer(&mut app, triggered("paddock", ActionOutcome::TimedOut));
        assert_eq!(state_of(&app), PaneState::Ready(a_pane()));
        assert_eq!(
            status(&app).failed(),
            Some("paddock did not answer in time")
        );

        answer(
            &mut app,
            triggered(
                "paddock",
                ActionOutcome::Replied {
                    body: a_pane().body().unwrap(),
                },
            ),
        );
        assert_eq!(status(&app).failed(), None, "a good answer clears it");
    }

    #[test]
    fn a_pull_nobody_took_ends_the_wait() {
        let mut app = pulling_paddock();
        app.update(Msg::Unsent {
            sent: pull_of("paddock"),
        });
        assert_eq!(
            state_of(&app),
            PaneState::Unavailable("paddock: the pane was not asked for".to_string())
        );
        let again = app.update(Msg::DogDeclaresPane {
            name: "paddock".to_string(),
            opening: OPENING,
            declared: Some(declared()),
        });
        assert_eq!(
            again,
            Effect::Send(pull_of("paddock")),
            "and may be asked again"
        );
    }

    #[test]
    fn an_answer_for_a_dog_the_operator_has_left_is_dropped() {
        let mut app = pulling_paddock();
        app.update(Msg::Key(KeyPress::Escape));
        assert!(app.config_pane().is_none());
        answer(&mut app, triggered("paddock", ActionOutcome::TimedOut));
        assert!(app.config_pane().is_none());
        assert!(app.notice().is_none(), "silently: nothing went wrong");

        // And a manifest read that lands late asks for nothing.
        let late = app.update(Msg::DogDeclaresPane {
            name: "paddock".to_string(),
            opening: OPENING,
            declared: Some(declared()),
        });
        assert_eq!(late, Effect::None);
    }

    #[test]
    fn an_answer_for_another_dogs_pull_does_not_land_on_this_pane() {
        let mut app = pulling_paddock();
        app.update(Msg::Replied {
            sent: pull_of("kelpie"),
            result: triggered("kelpie", ActionOutcome::TimedOut),
        });
        assert_eq!(state_of(&app), PaneState::Waiting);
    }

    /// The pane left and opened again: what was asked of the first is not
    /// what the second is waiting for.
    #[test]
    fn a_read_or_a_pull_from_an_earlier_opening_does_not_land_on_a_later_pane() {
        let mut app = pulling_paddock();
        app.update(Msg::Key(KeyPress::Escape));
        let (_, raised) = reopen(&mut app);
        assert_eq!(
            raised,
            Effect::ReadDogPane {
                name: "paddock".to_string(),
                opening: OPENING + 1,
                adopted_path: PathBuf::from("/opt/paddock"),
            }
        );

        // The first opening's manifest read lands on the second pane.
        let late = app.update(Msg::DogDeclaresPane {
            name: "paddock".to_string(),
            opening: OPENING,
            declared: Some(declared()),
        });
        assert_eq!(late, Effect::None);
        assert!(
            app.config_pane()
                .is_some_and(|pane| pane.status().is_none())
        );

        // The second's own read is sent, and the first's pull answers into it.
        let own = app.update(Msg::DogDeclaresPane {
            name: "paddock".to_string(),
            opening: OPENING + 1,
            declared: Some(declared()),
        });
        let Effect::Send(second) = own else {
            panic!("the second opening's own read asks");
        };
        answer(&mut app, triggered("paddock", ActionOutcome::TimedOut));
        assert_eq!(state_of(&app), PaneState::Waiting, "still waiting");
        app.update(Msg::Replied {
            sent: second,
            result: triggered("paddock", ActionOutcome::TimedOut),
        });
        assert_eq!(
            state_of(&app),
            PaneState::Unavailable("paddock did not answer in time".to_string())
        );
    }

    /// Opens `paddock`'s pane again on `app`, as [`open_dog_pane`] does.
    fn reopen(app: &mut App) -> (&mut App, Effect) {
        let Effect::LoadDogPane { adopted_path, .. } = app.update(Msg::Key(KeyPress::Edit)) else {
            panic!("`e` on a dog row probes its schema");
        };
        app.update(Msg::DogPane {
            name: "paddock".to_string(),
            adopted_path,
            env_keys: Vec::new(),
            result: Ok(serde_json::json!({
                "type": "object",
                "properties": { "ratio": { "type": "number" } },
            })),
        });
        let effect = app.update(Msg::Replied {
            sent: Sent::DogSection {
                name: "paddock".to_string(),
            },
            result: Ok(Response::DogSection {
                toml: "ratio = 1.5\n".to_string().into(),
            }),
        });
        (app, effect)
    }

    /// A re-read is not an opening, so a pull out under the pane still lands.
    #[test]
    fn a_re_read_does_not_make_an_opening_of_its_own() {
        let mut app = pulling_paddock();
        let again = app.update(Msg::Replied {
            sent: Sent::DogSection {
                name: "paddock".to_string(),
            },
            result: Ok(Response::DogSection {
                toml: "ratio = 2.5\n".to_string().into(),
            }),
        });
        assert_eq!(again, Effect::None);
        answer(&mut app, triggered("paddock", ActionOutcome::TimedOut));
        assert_eq!(
            state_of(&app),
            PaneState::Unavailable("paddock did not answer in time".to_string())
        );
    }

    /// A section reply for one dog can land while another's pane is open.
    #[test]
    fn a_pane_rebuilt_for_another_dog_takes_no_pull_from_the_open_one() {
        let pane_of = |name: &str| {
            ConfigPane::dog(
                name.to_string(),
                Some(PathBuf::from("/opt/x")),
                serde_json::json!({ "type": "object", "properties": {} }),
                String::new(),
                Vec::new(),
            )
        };
        let mut open = pane_of("paddock");
        open.declare_pane(declared());

        let mut other = pane_of("kelpie");
        other.adopt_status_from(&open);
        assert!(other.status().is_none(), "kelpie never declared a pane");

        let mut same = pane_of("paddock");
        same.adopt_status_from(&open);
        assert_eq!(
            same.status().map(DogStatus::declared),
            Some(&declared()),
            "a re-read of paddock's own keeps it"
        );
    }
}