shep-daemon 0.22.0

The supervision engine behind shep: process spawning, restart policy, the log plane, watch and cron restarts, and the RPC server
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
//! A dog's per-sheep tables: `DogSheepSettings` reads one dog's tables,
//! `SetSheepDogSettings` writes one, and a load merges `dogs` as one field.

use super::dog_defaults::set_default;
use super::dog_table_events::{heard, on};
use super::*;
use shep_core::config::DogTable;

/// A table from a JSON object literal.
///
/// # Panics
///
/// If `value` is not an object, which is a fixture bug.
pub(super) fn table(value: serde_json::Value) -> DogTable {
    let serde_json::Value::Object(map) = value else {
        panic!("a table fixture is an object")
    };
    DogTable::from(map)
}

/// `name` carrying one table per `(dog, table)` pair.
pub(super) fn carrying(name: &str, tables: Vec<(&str, DogTable)>) -> AppConfig {
    let mut app = AppConfig::minimal(name, "./srv");
    app.dogs = tables
        .into_iter()
        .map(|(dog, table)| (dog.to_string(), table))
        .collect();
    app
}

/// Starts `apps` and asserts the start landed.
pub(super) async fn start(ctx: &RpcContext, id: u64, apps: Vec<AppConfig>) {
    let started = reply_of(dispatch(envelope(id, Request::Start { apps }), ctx).await);
    assert!(started.result.is_ok(), "{:?}", started.result);
}

/// What `DogSheepSettings { dog }` answers.
async fn tables_for(ctx: &RpcContext, id: u64, dog: &str) -> BTreeMap<String, DogTable> {
    let reply = reply_of(
        dispatch(
            envelope(
                id,
                Request::DogSheepSettings {
                    dog: dog.to_string(),
                },
            ),
            ctx,
        )
        .await,
    );
    match reply.result {
        Ok(Response::DogSheepSettings { tables }) => tables,
        other => panic!("expected DogSheepSettings, got {other:?}"),
    }
}

/// Sends one `SetSheepDogSettings` and hands back the reply.
pub(super) async fn set_table(
    ctx: &RpcContext,
    id: u64,
    name: &str,
    dog: &str,
    table: Option<DogTable>,
) -> Result<Response, RpcError> {
    reply_of(
        dispatch(
            envelope(
                id,
                Request::SetSheepDogSettings {
                    name: name.to_string(),
                    dog: dog.to_string(),
                    table,
                },
            ),
            ctx,
        )
        .await,
    )
    .result
}

/// Asserts `reply` is the success answer for `name` and `dog`.
#[track_caller]
fn assert_set(reply: &Result<Response, RpcError>, name: &str, dog: &str) {
    assert_eq!(
        reply,
        &Ok(Response::SheepDogSettingsSet {
            name: name.to_string(),
            dog: dog.to_string(),
        })
    );
}

#[tokio::test(start_paused = true)]
async fn a_dog_reads_its_own_table_from_every_sheep_and_nobody_elses() {
    let h = harness(vec![ProcScript::never_exits(); 4]);
    let jobs_on_web = table(serde_json::json!({ "concurrency": 2, "hours": { "start": "09:00" } }));
    let deploy_on_web = table(serde_json::json!({ "branch": "main" }));
    let deploy_on_api = table(serde_json::json!({ "branch": "release" }));
    start(
        &h.ctx,
        1,
        vec![
            carrying(
                "web",
                vec![
                    ("jobs", jobs_on_web.clone()),
                    ("deploy", deploy_on_web.clone()),
                ],
            ),
            carrying("api", vec![("deploy", deploy_on_api.clone())]),
            carrying("worker", Vec::new()),
        ],
    )
    .await;
    enable_dog(&h.ctx, 2, "bark").await;

    assert_eq!(
        tables_for(&h.ctx, 3, "jobs").await,
        BTreeMap::from([("web".to_string(), jobs_on_web)]),
        "api carries only another dog's table and worker carries none"
    );
    assert_eq!(
        tables_for(&h.ctx, 4, "deploy").await,
        BTreeMap::from([
            ("api".to_string(), deploy_on_api),
            ("web".to_string(), deploy_on_web),
        ])
    );
    assert_eq!(
        tables_for(&h.ctx, 5, "nobody").await,
        BTreeMap::new(),
        "a dog nobody names is an empty map, never NotFound"
    );
    assert_eq!(tables_for(&h.ctx, 6, "bark").await, BTreeMap::new());
}

/// Set, replace and remove, each asserted against the second dog's
/// table on the same sheep: the write builds a whole `dogs` map, and a
/// map built from the wrong base would drop it.
#[tokio::test(start_paused = true)]
async fn a_write_sets_replaces_and_removes_one_table_and_leaves_the_other_dogs() {
    let h = harness(vec![ProcScript::never_exits()]);
    let deploy = table(serde_json::json!({ "branch": "main" }));
    start(
        &h.ctx,
        1,
        vec![carrying("web", vec![("deploy", deploy.clone())])],
    )
    .await;
    let first = table(serde_json::json!({ "concurrency": 2 }));
    let second = table(serde_json::json!({ "concurrency": 4, "merge": { "mode": "ask" } }));

    for (id, next) in [(2, Some(first)), (4, Some(second)), (6, None)] {
        let reply = set_table(&h.ctx, id, "web", "jobs", next.clone()).await;
        assert_set(&reply, "web", "jobs");
        let expected = next.map_or_else(BTreeMap::new, |next| {
            BTreeMap::from([("web".to_string(), next)])
        });
        assert_eq!(tables_for(&h.ctx, id + 1, "jobs").await, expected);
        assert_eq!(
            tables_for(&h.ctx, id + 1, "deploy").await,
            BTreeMap::from([("web".to_string(), deploy.clone())]),
            "the write to jobs moved deploy's table"
        );
    }
}

/// Recorded as an override of the whole field, so both the pane's `*`
/// and the CFG column name it, and recorded to the roll, because nothing
/// on the restore path reads the override store.
#[tokio::test(start_paused = true)]
async fn a_write_is_an_operator_override_of_dogs_and_reaches_the_muster_roll() {
    let h = harness(vec![ProcScript::never_exits()]);
    start(&h.ctx, 1, vec![carrying("web", Vec::new())]).await;
    // An unrelated override the write must leave standing.
    let restarts = reply_of(
        dispatch(
            envelope(
                3,
                Request::SetSheepField {
                    name: "web".to_string(),
                    key: "max_restarts".to_string(),
                    value: serde_json::json!(40),
                },
            ),
            &h.ctx,
        )
        .await,
    );
    assert!(restarts.result.is_ok(), "{:?}", restarts.result);

    let jobs = table(serde_json::json!({ "concurrency": 2, "token": "hunter2" }));
    let reply = set_table(&h.ctx, 4, "web", "jobs", Some(jobs.clone())).await;
    assert_set(&reply, "web", "jobs");

    let stored = shep_core::overrides::get(&h.ctx.paths.overrides, "web")
        .unwrap()
        .expect("the write is recorded");
    assert_eq!(
        stored.fields["dogs"],
        serde_json::json!({ "jobs": { "concurrency": 2, "token": "hunter2" } })
    );
    assert_eq!(stored.fields["max_restarts"], 40, "an unrelated override");

    let view = sheep_config_view(&h.ctx, 5, "web").await;
    assert_eq!(view.overridden, ["dogs", "max_restarts"]);
    let infos = list_flock(&h.ctx, 6).await;
    let web = infos.iter().find(|info| info.name == "web").unwrap();
    assert_eq!(
        web.overridden.as_deref(),
        Some(&["dogs".to_string(), "max_restarts".to_string()][..])
    );

    let roll = h.ctx.registry.roll(&infos, 0);
    let entry = roll
        .apps
        .iter()
        .find(|entry| entry.app.name == "web")
        .expect("web is in the roll");
    assert_eq!(entry.app.dogs, BTreeMap::from([("jobs".to_string(), jobs)]));
    assert_eq!(entry.app.max_restarts, 40);
}

/// A dog runs at the daemon's own trust level and is never in the
/// override store; the store is asserted as well as the code, since a
/// refusal that still wrote would be the same hole with a better error.
#[tokio::test(start_paused = true)]
async fn a_dogs_own_name_is_refused_and_an_unknown_sheep_is_not_found() {
    let h = harness(vec![ProcScript::never_exits()]);
    enable_dog(&h.ctx, 1, "bark").await;
    let jobs = table(serde_json::json!({ "concurrency": 2 }));

    let Err(err) = set_table(&h.ctx, 2, "bark", "jobs", Some(jobs.clone())).await else {
        panic!("a dog was given a table")
    };
    assert_eq!(err.code, RpcErrorCode::InvalidConfig);
    assert!(err.message.contains("bark is a dog"), "{}", err.message);
    assert!(
        shep_core::overrides::get(&h.ctx.paths.overrides, "bark")
            .unwrap()
            .is_none(),
        "the refusal still wrote the store"
    );

    let Err(err) = set_table(&h.ctx, 3, "ghost", "jobs", Some(jobs)).await else {
        panic!("a sheep nobody registered took a table")
    };
    assert_eq!(err.code, RpcErrorCode::NotFound);
}

/// `normalize` refuses an empty dog name the way it refuses one in a
/// Flockfile; the write is checked before the store is touched, so the
/// refusal leaves it untouched too.
#[tokio::test(start_paused = true)]
async fn an_empty_dog_name_is_refused_and_writes_nothing() {
    let h = harness(vec![ProcScript::never_exits()]);
    start(&h.ctx, 1, vec![carrying("web", Vec::new())]).await;
    let jobs = table(serde_json::json!({ "concurrency": 2 }));

    let Err(err) = set_table(&h.ctx, 2, "web", "", Some(jobs)).await else {
        panic!("an empty dog name was accepted")
    };
    assert_eq!(err.code, RpcErrorCode::InvalidConfig);
    assert!(
        shep_core::overrides::get(&h.ctx.paths.overrides, "web")
            .unwrap()
            .is_none(),
        "the refusal still wrote the store"
    );
}

/// A whole-map write from a pane editing one dog would overwrite a
/// concurrent edit to another dog's table.
#[tokio::test(start_paused = true)]
async fn set_sheep_field_refuses_dogs_and_names_the_request_that_owns_it() {
    let h = harness(vec![ProcScript::never_exits()]);
    start(&h.ctx, 1, vec![carrying("web", Vec::new())]).await;

    let reply = reply_of(
        dispatch(
            envelope(
                2,
                Request::SetSheepField {
                    name: "web".to_string(),
                    key: "dogs".to_string(),
                    value: serde_json::json!({ "jobs": { "concurrency": 2 } }),
                },
            ),
            &h.ctx,
        )
        .await,
    );
    let Err(err) = reply.result else {
        panic!("a whole dogs map was accepted")
    };
    assert_eq!(err.code, RpcErrorCode::InvalidConfig);
    assert!(
        err.message.contains("SetSheepDogSettings"),
        "{}",
        err.message
    );
    assert!(
        shep_core::overrides::get(&h.ctx.paths.overrides, "web")
            .unwrap()
            .is_none(),
        "the refusal still wrote the store"
    );
}

/// `web` declaring `dogs` with `concurrency` at `n`, as a Flockfile would.
pub(super) fn declared_jobs(n: u64) -> DeclaredApp {
    DeclaredApp {
        config: carrying(
            "web",
            vec![("jobs", table(serde_json::json!({ "concurrency": n })))],
        ),
        declared: ["dogs".to_string()].into_iter().collect(),
        declared_env: BTreeSet::new(),
    }
}

/// Sends one `ApplyConfig` of `app` at `reset` and hands back its report.
pub(super) async fn apply(
    ctx: &RpcContext,
    id: u64,
    app: DeclaredApp,
    reset: ResetDepth,
) -> shep_core::protocol::SheepApplied {
    let reply = reply_of(
        dispatch(
            envelope(
                id,
                Request::ApplyConfig {
                    apps: vec![app],
                    reset,
                },
            ),
            ctx,
        )
        .await,
    );
    let Ok(Response::Applied(mut report)) = reply.result else {
        panic!("expected Applied, got {:?}", reply.result)
    };
    report.remove(0)
}

/// `dogs` merges as one field, the way `level_rules` does: once a load has
/// established it, a plain load of a changed table leaves the stored one
/// and the drift report names it, `--reset=env` leaves it too, and
/// `--reset=file` applies it.
#[tokio::test(start_paused = true)]
async fn a_plain_load_leaves_an_established_table_and_reset_file_applies_it() {
    let h = harness(vec![ProcScript::never_exits()]);
    start(&h.ctx, 1, vec![AppConfig::minimal("web", "./srv")]).await;
    let first = apply(&h.ctx, 2, declared_jobs(2), ResetDepth::None).await;
    assert_eq!(first.applied, ["dogs"], "nobody had established it yet");
    let in_force = tables_for(&h.ctx, 3, "jobs").await;

    for (id, reset) in [(4, ResetDepth::None), (6, ResetDepth::Env)] {
        let report = apply(&h.ctx, id, declared_jobs(4), reset).await;
        assert!(report.applied.is_empty(), "{reset:?}: {report:?}");
        assert_eq!(
            tables_for(&h.ctx, id + 1, "jobs").await,
            in_force,
            "{reset:?} moved an established table"
        );
    }
    let drift = reply_of(
        dispatch(
            envelope(
                8,
                Request::ConfigDrift {
                    apps: vec![declared_jobs(4).config],
                },
            ),
            &h.ctx,
        )
        .await,
    );
    let Ok(Response::Drifted(drifted)) = drift.result else {
        panic!("expected Drifted, got {:?}", drift.result)
    };
    assert_eq!(drifted.len(), 1);
    assert_eq!(drifted[0].fields, ["dogs"]);

    let report = apply(&h.ctx, 9, declared_jobs(4), ResetDepth::File).await;
    assert_eq!(report.applied, ["dogs"]);
    assert_eq!(
        tables_for(&h.ctx, 10, "jobs").await,
        BTreeMap::from([(
            "web".to_string(),
            table(serde_json::json!({ "concurrency": 4 }))
        )])
    );
}

/// `web` and `api` carry `jobs`, `worker` carries only `deploy`, and
/// `batch` carries `jobs` with its own value for the one key the default
/// moves: a default write announces the two sheep whose layered table
/// moved, the same write again announces none, and removing it announces
/// the two again.
#[tokio::test(start_paused = true)]
async fn a_default_change_announces_every_sheep_whose_layered_table_moved() {
    let h = harness(vec![ProcScript::never_exits(); 4]);
    let mut rx = h.ctx.events.subscribe();
    let jobs = |model: &str| table(serde_json::json!({ "model": model }));
    start(
        &h.ctx,
        1,
        vec![
            carrying("web", vec![("jobs", table(serde_json::json!({})))]),
            carrying(
                "api",
                vec![("jobs", table(serde_json::json!({ "hours": 1 })))],
            ),
            carrying("worker", vec![("deploy", table(serde_json::json!({})))]),
            carrying("batch", vec![("jobs", jobs("sonnet"))]),
        ],
    )
    .await;
    heard(&h.ctx, &mut rx).await;

    set_default(&h.ctx, 2, "jobs", Some(jobs("opus"))).await;
    let events = heard(&h.ctx, &mut rx).await;
    assert_eq!(
        on("config.sheep.jobs", &events),
        [
            ("jobs".to_string(), "api".to_string()),
            ("jobs".to_string(), "web".to_string()),
        ],
        "batch holds its own model and worker has no jobs table"
    );
    assert_eq!(on("config.sheep.*", &events).len(), 2, "{events:?}");

    set_default(&h.ctx, 3, "jobs", Some(jobs("opus"))).await;
    assert_eq!(
        heard(&h.ctx, &mut rx).await,
        [],
        "the same default moved nothing"
    );

    set_default(&h.ctx, 4, "jobs", None).await;
    assert_eq!(
        on("config.sheep.jobs", &heard(&h.ctx, &mut rx).await),
        [
            ("jobs".to_string(), "api".to_string()),
            ("jobs".to_string(), "web".to_string()),
        ]
    );
}