shep 0.22.0

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
//! The settings screen's own reader and writer: the one place `shep.toml`'s
//! raw text meets [`DaemonConfig`]'s opinion about whether a value is legal.
//!
//! Validation lives in [`apply_setting`], the only function that puts a
//! mutated [`ShepToml`] and a real [`DaemonConfig::load`] in one place.
//!
//! [`load_settings`] reads the document, never a loaded [`DaemonConfig`]: a
//! loaded config cannot tell a key written at its own default from a key
//! nobody wrote, which is the distinction this screen exists to show.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use serde_json::{Map, Value};
use shep_core::config::{DaemonConfig, DaemonConfigError, parse_daemon_bool};

use crate::commands::shep_toml::{GrantRecord, PathError, ShepToml, ShepTomlError};
use crate::dog::BUILT_IN_DOGS;
use crate::lookout::field::{Field, FieldKind, segment, shep_toml_shape};
use crate::style::{StyleLevel, StyleSource};

#[cfg(test)]
mod tests;

// `crate::style::StyleSource` is reused for "which layer decided". Only
// `style.level` ever reads as `Flag` or `Env`: the shepherd's own env and
// flags are invisible here, so every other key is `Config` or `Default`.
// `Config` says the key is in the file, not that the shepherd is using it.

/// One value as the screen shows it
///
/// `Debug` is derived, not redacted: a rendered string and a layer name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScalarView {
    /// Already rendered for display, defaults resolved.
    pub value: String,
    /// Which layer this value came from.
    pub source: StyleSource,
}

/// What kind of TOML value a typed edit becomes.
///
/// `Debug` is derived, not redacted: a bare variant name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
    /// `true` or `false`, in the daemon's own spellings.
    Bool,
    /// A whole number.
    Integer,
    /// A number with or without a fraction.
    Number,
    /// A string, as typed.
    Text,
    /// An array of strings, typed comma-separated.
    List,
}

impl Shape {
    /// The shape an edit of `kind` writes, or [`None`] for a kind the
    /// screen cannot write as one value.
    #[must_use]
    pub fn of(kind: &FieldKind) -> Option<Self> {
        match kind {
            FieldKind::Bool => Some(Self::Bool),
            FieldKind::Integer => Some(Self::Integer),
            FieldKind::Number => Some(Self::Number),
            FieldKind::Text | FieldKind::Choice(_) | FieldKind::Suggested(_) => Some(Self::Text),
            FieldKind::List(_) => Some(Self::List),
            FieldKind::Map | FieldKind::Entries(_) | FieldKind::Union(_) | FieldKind::Opaque => {
                None
            }
        }
    }

    /// `text` as a TOML value of this shape.
    fn parse(self, text: &str) -> Result<toml_edit::Value, SettingError> {
        let invalid = |what: &str| SettingError::Invalid(format!("{text} is not {what}"));
        Ok(match self {
            Self::Bool => parse_daemon_bool(text)
                .ok_or_else(|| invalid("a valid boolean"))?
                .into(),
            Self::Integer => text
                .trim()
                .parse::<i64>()
                .map_err(|_| invalid("a whole number"))?
                .into(),
            Self::Number => text
                .trim()
                .parse::<f64>()
                .map_err(|_| invalid("a number"))?
                .into(),
            Self::Text => text.into(),
            Self::List => text
                .split(',')
                .map(str::trim)
                .filter(|item| !item.is_empty())
                .collect::<toml_edit::Array>()
                .into(),
        })
    }
}

/// One edit, ready to apply
///
/// `Debug` is derived, not redacted: a key path and the text typed for it.
/// Nothing in `shep.toml`'s own schema is a secret: `secrets.allow_read`
/// names environment variables, never their values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SettingEdit {
    /// Write `value` at `path`.
    Set {
        /// The key, as its segments: `["daemon", "log_level"]`, or
        /// `["interpreters", "py"]` for one entry of a map.
        path: Vec<String>,
        /// What the text becomes.
        shape: Shape,
        /// The text as typed or chosen, unparsed until [`apply_setting`]
        /// validates it.
        value: String,
    },
    /// Remove the key at `path`, returning it to the compiled default.
    Unset {
        /// The key, as its segments.
        path: Vec<String>,
    },
}

impl SettingEdit {
    /// The key's segments.
    #[must_use]
    pub fn path(&self) -> &[String] {
        match self {
            Self::Set { path, .. } | Self::Unset { path } => path,
        }
    }

    /// The key as the screen names it: segments joined by dots, each
    /// quoted when TOML would quote it.
    #[must_use]
    pub fn key(&self) -> String {
        dotted(self.path())
    }
}

/// `path` as a dotted key.
pub(crate) fn dotted(path: &[String]) -> String {
    path.iter()
        .map(|key| segment(key))
        .collect::<Vec<_>>()
        .join(".")
}

/// Everything the screen reads off disk in one go
///
/// `Debug` is derived, not redacted: a dog's own webhook token lives in
/// `dogs.toml`, which this type never reads, and `shep.toml`'s schema names
/// no secret.
#[derive(Debug, Clone, PartialEq)]
pub struct SettingsSnapshot {
    /// The document as JSON. A section the file never wrote is absent.
    pub document: Map<String, Value>,
    /// The socket this lookout is connected over, which an absent
    /// `daemon.socket` shows.
    pub socket_default: PathBuf,
    /// `style.level`, resolved: the level in force and the layer that set it.
    ///
    /// `--style` and `$SHEP_STYLE` are lookout's own, so this can differ from
    /// what the document says. [`Self::file_value`] reads the document's half.
    pub style: (StyleLevel, StyleSource),
    /// Every candidate dog: [`BUILT_IN_DOGS`] plus every `adopted_dogs`
    /// key, sorted, deduplicated.
    pub dogs: Vec<DogView>,
}

impl SettingsSnapshot {
    /// What the document says at the dotted `key`, or [`None`] when it
    /// never wrote it.
    #[must_use]
    pub fn file_value(&self, key: &str) -> Option<&Value> {
        let path = shep_toml_shape().paths.get(key)?;
        let (first, rest) = path.split_first()?;
        let mut value = self.document.get(first)?;
        for segment in rest {
            value = value.as_object()?.get(segment)?;
        }
        (!value.is_null()).then_some(value)
    }

    /// The entries of the map at the dotted `key`, in key order.
    #[must_use]
    pub fn entries(&self, key: &str) -> Vec<(String, String)> {
        self.file_value(key)
            .and_then(Value::as_object)
            .map(|map| {
                map.iter()
                    .map(|(name, value)| (name.clone(), render_value(value)))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// What the screen shows for `field`: the file's value, else the
    /// default.
    #[must_use]
    pub fn view(&self, field: &Field) -> ScalarView {
        if field.key == STYLE_LEVEL_KEY {
            return ScalarView {
                value: self.style.0.to_string(),
                source: self.style.1,
            };
        }
        if let Some(value) = self.file_value(&field.key) {
            return ScalarView {
                value: render_value(value),
                source: StyleSource::Config,
            };
        }
        let value = if field.key == SOCKET_KEY {
            self.socket_default.display().to_string()
        } else {
            field
                .default_value
                .as_ref()
                .map_or_else(|| "not set".to_owned(), render_value)
        };
        ScalarView {
            value,
            source: StyleSource::Default,
        }
    }

    /// The text an editor on `field` opens with, as it would be typed: what
    /// the file says, else the value the key has without it.
    #[must_use]
    pub fn seed(&self, field: &Field) -> String {
        if let Some(value) = self.file_value(&field.key) {
            return typed_text(value);
        }
        if field.key == SOCKET_KEY {
            return self.socket_default.display().to_string();
        }
        field
            .default_value
            .as_ref()
            .map(typed_text)
            .unwrap_or_default()
    }
}

/// `value` as one would type it into an editor: a string bare, a list comma
/// separated.
fn typed_text(value: &Value) -> String {
    match value {
        Value::String(text) => text.clone(),
        Value::Array(items) => items
            .iter()
            .map(|item| {
                item.as_str()
                    .map_or_else(|| item.to_string(), str::to_owned)
            })
            .collect::<Vec<_>>()
            .join(", "),
        other => other.to_string(),
    }
}

/// The settings key whose value `--style` and `$SHEP_STYLE` can outrank.
pub(crate) const STYLE_LEVEL_KEY: &str = "style.level";
/// The settings key whose absence shows the socket lookout connected over.
pub(crate) const SOCKET_KEY: &str = "daemon.socket";

/// `value` as one cell: strings bare, a list joined, an empty one `none`.
fn render_value(value: &Value) -> String {
    match value {
        Value::Null => "not set".to_owned(),
        Value::String(text) => text.clone(),
        Value::Array(items) if items.is_empty() => "none".to_owned(),
        Value::Array(_) => typed_text(value),
        Value::Object(map) if map.is_empty() => "none".to_owned(),
        Value::Object(map) if map.len() == 1 => "1 entry".to_owned(),
        Value::Object(map) => format!("{} entries", map.len()),
        other => other.to_string(),
    }
}

/// One dog's row on the settings screen: the file joined against the flock,
/// and the four `[daemon]` keys that belong to that one dog.
///
/// `Debug` is derived, not redacted: a name, three bools, a binary's path, the
/// names of its `env` keys and what `[daemon] dog_grants` records, which is
/// permission names and never a value. The dog's own config, which can hold a
/// secret, lives in `dogs.toml` and is not here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DogView {
    /// The dog's name.
    pub name: String,
    /// Whether `[daemon] enabled_dogs` names it.
    pub enabled: bool,
    /// `None` for a built-in dog; the adopted binary's path otherwise.
    pub adopted_path: Option<PathBuf>,
    /// Whether `[daemon] boot_first_dogs` names it: the next boot starts it
    /// ahead of the whole flock.
    pub boot_first: bool,
    /// Whether `[daemon] channel_dogs` names it. Read-only here: it is what
    /// the dog's binary asked for when `shep adopt` ran it, not a setting.
    pub channel: bool,
    /// What `[daemon] dog_grants.<name>]` records.
    pub grants: DogGrants,
    /// The permissions the settings screen offers as a checklist under this
    /// dog's `grants` row: what its manifest declares, for a dog that has a
    /// `[daemon] dog_grants` record. Empty for a dog with no record.
    ///
    /// Read off the file rather than off the dog's binary: an adopted dog's
    /// record was written out of its manifest when `shep enable` asked.
    pub offered: Vec<String>,
    /// The names of the `env` keys the dog's `[daemon] adopted_dogs` entry
    /// sets, in key order. Empty for a built-in dog, which has no entry to
    /// hold one.
    ///
    /// Names only: a value never leaves `shep.toml` for a screen to hold.
    pub env_keys: Vec<String>,
}

impl DogView {
    /// A built-in dog with nothing recorded beyond `enabled`: no
    /// `adopted_dogs` entry, not boot first, not on the channel, no grants.
    ///
    /// A real state a `shep.toml` can hold, and the one a test that only
    /// needs a dog on screen means to name.
    #[cfg_attr(
        not(test),
        allow(
            dead_code,
            reason = "the dog fixtures in `lookout::view::fixtures` and `lookout::frames::fixtures` \
                      are the only callers; `load_settings` builds every live row field by field"
        )
    )]
    #[must_use]
    pub fn built_in(name: &str, enabled: bool) -> Self {
        Self {
            name: name.to_owned(),
            enabled,
            adopted_path: None,
            boot_first: false,
            channel: false,
            grants: DogGrants::Undeclared,
            offered: Vec::new(),
            env_keys: Vec::new(),
        }
    }

    /// An adopted dog whose binary is `path`, with nothing else recorded.
    #[cfg_attr(
        not(test),
        allow(
            dead_code,
            reason = "the dog fixtures in `lookout::view::fixtures` and `lookout::frames::fixtures`                       are the only callers; `load_settings` builds every live row field by field"
        )
    )]
    #[must_use]
    pub fn adopted(name: &str, enabled: bool, path: &Path) -> Self {
        Self {
            adopted_path: Some(path.to_path_buf()),
            ..Self::built_in(name, enabled)
        }
    }
}

/// What `[daemon] dog_grants.<name>]` says about one dog.
///
/// Three answers rather than an `Option`, because "no entry" and "an entry
/// shep cannot read" are different facts and the second one means the next
/// boot refuses the file.
///
/// `Debug` is derived, not redacted: [`GrantRecord`] holds permission names.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DogGrants {
    /// No entry. The dog declares nothing and runs with full access, or was
    /// never asked, which is what `shep enable` asks about.
    Undeclared,
    /// The recorded entry.
    Recorded(GrantRecord),
    /// The entry is there and the shepherd could not read it. Carries the
    /// refusal, which names the dog and what is wrong.
    Unreadable(String),
}

impl DogGrants {
    /// Every permission the record names, in `granted`, `waiting` or
    /// `revoked`: the set the operator has been asked about.
    ///
    /// An undeclared dog has none, and an unreadable one has none worth
    /// naming. [`DogView::offered`] is this filtered by what the dog declares.
    #[must_use]
    pub fn permissions(&self) -> Vec<String> {
        let Self::Recorded(record) = self else {
            return Vec::new();
        };
        let mut names: BTreeSet<&str> = BTreeSet::new();
        names.extend(record.granted.names());
        names.extend(record.waiting.names());
        names.extend(record.revoked.names());
        names.into_iter().map(str::to_owned).collect()
    }

    /// Whether the record grants `permission`.
    #[must_use]
    pub fn grants(&self, permission: &str) -> bool {
        let Self::Recorded(record) = self else {
            return false;
        };
        record.granted.names().any(|held| held == permission)
    }
}

/// What [`apply_setting`] can fail with
///
/// `Debug` is derived, not redacted: [`Self::Config`] forwards to
/// [`ShepTomlError`]'s own redacted `Debug`, and [`Self::Invalid`] carries
/// a refusal message naming a key and a rule, never a value from the file.
#[derive(Debug)]
pub enum SettingError {
    /// [`ShepToml::try_edit`]'s setup or write failed: the lock, the read,
    /// or the rename.
    Config(ShepTomlError),
    /// [`DaemonConfig::load`] refused the document this edit would have
    /// written, or the value is not legal for its key. Carries the refusal
    /// message, so the operator is told which key and why.
    Invalid(String),
}

impl std::fmt::Display for SettingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Config(err) => write!(f, "{err}"),
            Self::Invalid(message) => write!(f, "{message}"),
        }
    }
}

impl core::error::Error for SettingError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Config(err) => Some(err),
            Self::Invalid(_) => None,
        }
    }
}

impl From<ShepTomlError> for SettingError {
    fn from(err: ShepTomlError) -> Self {
        Self::Config(err)
    }
}

impl From<PathError> for SettingError {
    fn from(err: PathError) -> Self {
        Self::Invalid(err.to_string())
    }
}

/// Reads the snapshot, taking no lock: see [`ShepToml::read_only`]
///
/// `socket_default` is the socket this lookout is connected over, so an
/// absent `daemon.socket` shows the live answer rather than a guess.
/// `style` is `resolve_style`'s already-resolved pair.
///
/// # Errors
/// [`ShepTomlError::Io`] if `path` exists and could not be read.
/// [`ShepTomlError::Parse`] if `path` exists and is not valid TOML.
pub fn load_settings(
    path: &Path,
    socket_default: &Path,
    style: (StyleLevel, StyleSource),
) -> Result<SettingsSnapshot, ShepTomlError> {
    let doc = ShepToml::read_only(path)?;
    Ok(snapshot_of(&doc, socket_default, style))
}

/// [`load_settings`] over a document already in hand.
pub(crate) fn snapshot_of(
    doc: &ShepToml,
    socket_default: &Path,
    style: (StyleLevel, StyleSource),
) -> SettingsSnapshot {
    SettingsSnapshot {
        document: doc.to_json(),
        socket_default: socket_default.to_path_buf(),
        style,
        dogs: dog_candidates(doc),
    }
}

/// Every candidate dog: [`BUILT_IN_DOGS`] plus every adopted name, sorted
/// and deduplicated, each paired with whether it is enabled and its path.
///
/// `pub(crate)`: lookout's dogs sub-screen probes the same list.
pub(crate) fn dog_candidates(doc: &ShepToml) -> Vec<DogView> {
    let enabled = doc.enabled_dog_names();
    let boot_first = doc.boot_first_dog_names();
    let mut names: BTreeSet<String> = BUILT_IN_DOGS
        .iter()
        .map(|name| (*name).to_string())
        .collect();
    names.extend(doc.adopted_dog_names());
    names
        .into_iter()
        .map(|name| {
            let adopted_path = doc.adopted_dog_path(&name);
            let is_enabled = enabled.contains(&name);
            let is_first = boot_first.contains(&name);
            let channel = doc.asked_for_channel(&name);
            let grants = match doc.grant_record(&name) {
                Ok(None) => DogGrants::Undeclared,
                Ok(Some(record)) => DogGrants::Recorded(record),
                Err(err) => DogGrants::Unreadable(err.to_string()),
            };
            let offered = offered(&name, adopted_path.is_none(), &grants);
            let env_keys = doc.adopted_dog_env(&name).into_keys().collect();
            DogView {
                name,
                enabled: is_enabled,
                adopted_path,
                boot_first: is_first,
                channel,
                grants,
                offered,
                env_keys,
            }
        })
        .collect()
}

/// The checklist the settings screen offers under `name`'s `grants` row.
///
/// A dog with no `[daemon] dog_grants` entry offers nothing, which is the same
/// fact [`crate::commands::dogs::record_change`] refuses on.
///
/// A built-in dog's checklist is what this binary declares; an adopted dog's
/// is its record, written out of its manifest when `shep enable` asked.
fn offered(name: &str, built_in: bool, grants: &DogGrants) -> Vec<String> {
    if !matches!(grants, DogGrants::Recorded(_)) {
        return Vec::new();
    }
    let recorded = grants.permissions();
    if !built_in {
        return recorded;
    }
    crate::dog::builtin_manifest(name).map_or(recorded, |manifest| {
        manifest
            .permissions
            .into_iter()
            .map(|declared| declared.name)
            .collect()
    })
}

/// Applies one edit under the config lock, validating before it saves
///
/// A value outside a key's closed set is refused first. The mutated
/// document is then loaded with `&|_| None` in place of an env layer: this
/// process's environment is not the shepherd's. A loader `Err` returns
/// before [`ShepToml::try_edit`] saves, leaving the file untouched down to
/// its inode.
///
/// # Errors
/// [`SettingError::Config`] if the lock, the read or the write failed.
/// [`SettingError::Invalid`] if the value is not legal for its key, a table
/// above the key is something else in the file, or [`DaemonConfig::load`]
/// refuses the document the edit would leave.
pub fn apply_setting(path: &Path, edit: &SettingEdit) -> Result<(), SettingError> {
    check_closed_set(edit)?;
    ShepToml::try_edit(path, |doc| -> Result<(), SettingError> {
        match edit {
            SettingEdit::Set { path, shape, value } => doc.set_path(path, shape.parse(value)?)?,
            SettingEdit::Unset { path } => doc.unset_path(path),
        }
        let rendered = doc.rendered();
        DaemonConfig::load(Some(&rendered), &|_| None)
            .map_err(|err: DaemonConfigError| SettingError::Invalid(err.to_string()))?;
        Ok(())
    })
}

/// Refuses a [`SettingEdit::Set`] whose key is a closed set and whose value
/// is not in it. The loader does not look at every such key: `[style]` is
/// parsed only so an unknown key is not an error.
fn check_closed_set(edit: &SettingEdit) -> Result<(), SettingError> {
    let SettingEdit::Set { value, .. } = edit else {
        return Ok(());
    };
    let Some(Field {
        kind: FieldKind::Choice(names),
        ..
    }) = shep_toml_shape().fields.by_key(&edit.key())
    else {
        return Ok(());
    };
    if names.contains(value) {
        Ok(())
    } else {
        Err(SettingError::Invalid(format!(
            "{value} is not one of {}",
            names.join(", ")
        )))
    }
}