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
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
//! Everything that is not big enough for its own file: `Ping`,
//! `HostUsage`, a bad selector or peer regex, `Describe`'s fold
//! filter, `Reopen`, single-target `Reload`, `Subscribe`, `KillDaemon`,
//! `SaveRoll`, and the deadline/budget plumbing every verb rides on.

use super::*;

#[tokio::test(start_paused = true)]
async fn ping_answers_pong_on_the_same_envelope_id() {
    let h = harness(vec![]);
    let reply = reply_of(dispatch(envelope(9, Request::Ping), &h.ctx).await);
    assert_eq!(reply.id, 9);
    assert_eq!(reply.result.unwrap(), Response::Pong);
}

/// The door a listing actually knocks on. `HostState`'s own tests prove
/// the tick writes and the reader does not sample; this one proves the
/// request reaches that reader at all, which no test of the state alone
/// can see.
#[tokio::test(start_paused = true)]
async fn host_usage_serves_the_reading_the_tick_left_behind() {
    let mut h = harness(vec![]);
    h.ctx.host = crate::host::HostState::fixed(Some(HostUsage {
        cpu_percent: Some(11.5),
        memory_used_bytes: 39_963_869_184,
        memory_total_bytes: 51_539_607_552,
        disk_bytes_per_second: Some((1_258_291, 491_520)),
        network_bytes_per_second: Some((24_594, 9_260)),
    }));

    let reply = reply_of(dispatch(envelope(1, Request::HostUsage), &h.ctx).await);

    let Response::HostUsage(Some(usage)) = reply.result.unwrap() else {
        panic!("expected a host reading")
    };
    assert_eq!(usage.cpu_percent, Some(11.5));
    assert_eq!(usage.memory_used_bytes, 39_963_869_184);
    assert_eq!(usage.disk_bytes_per_second, Some((1_258_291, 491_520)));
    assert_eq!(usage.network_bytes_per_second, Some((24_594, 9_260)));
}

/// A platform `sysinfo` cannot read is not an error, and answering one
/// with `RpcErrorCode::Internal` would fail a listing over a
/// decoration. The harness default is exactly this state.
#[tokio::test(start_paused = true)]
async fn a_host_that_cannot_be_read_answers_none_rather_than_failing() {
    let h = harness(vec![]);

    let reply = reply_of(dispatch(envelope(1, Request::HostUsage), &h.ctx).await);

    assert_eq!(reply.result.unwrap(), Response::HostUsage(None));
}
#[tokio::test(start_paused = true)]
async fn a_selector_matching_nothing_is_not_found() {
    let h = harness(vec![]);
    let reply = reply_of(
        dispatch(
            envelope(
                1,
                Request::Stop {
                    selector: SelectorSpec::Name("ghost".to_string()),
                },
            ),
            &h.ctx,
        )
        .await,
    );
    assert_eq!(reply.result.unwrap_err().code, RpcErrorCode::NotFound);
}

#[tokio::test(start_paused = true)]
async fn a_bad_peer_regex_is_invalid_config_not_a_panic() {
    let h = harness(vec![]);
    let reply = reply_of(
        dispatch(
            envelope(
                1,
                Request::Describe {
                    selector: SelectorSpec::Regex("((".to_string()),
                },
            ),
            &h.ctx,
        )
        .await,
    );
    assert_eq!(reply.result.unwrap_err().code, RpcErrorCode::InvalidConfig);
}

#[tokio::test(start_paused = true)]
async fn describe_filters_by_fold() {
    let h = harness(vec![ProcScript::never_exits(), ProcScript::never_exits()]);
    let mut api = AppConfig::minimal("api", "./a");
    api.fold = Some("backend".to_string());
    dispatch(
        envelope(
            1,
            Request::Start {
                apps: vec![api, AppConfig::minimal("web", "./w")],
            },
        ),
        &h.ctx,
    )
    .await;
    let hits = describe(&h.ctx, 2, SelectorSpec::Fold("backend".to_string())).await;
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].name, "api");
}

/// Fails if `Reopen` is left to `run`'s catch-all arm, which answers
/// `Internal` for a request this daemon implements, or if it is routed
/// to another verb's supervisor call: `Stop` would stop the sheep.
#[tokio::test(start_paused = true)]
async fn reopen_routes_to_the_supervisor_and_leaves_the_sheep_running() {
    let h = harness(vec![ProcScript::never_exits()]);
    start_web(&h).await;

    let reply = reply_of(
        dispatch(
            envelope(
                2,
                Request::Reopen {
                    selector: SelectorSpec::Name("web".to_string()),
                },
            ),
            &h.ctx,
        )
        .await,
    );
    let Response::Reopened(infos) = reply.result.unwrap() else {
        panic!("expected reopened")
    };
    assert_eq!(infos.len(), 1);
    assert_eq!(infos[0].status, ProcStatus::Online);

    let flock = list_flock(&h.ctx, 3).await;
    assert_eq!(
        flock[0].status,
        ProcStatus::Online,
        "a reopen must not disturb the sheep it reopens"
    );
}

/// Fails if `Reset` is left to `run`'s catch-all arm, which answers
/// `Internal`, or if it is routed to another verb's supervisor call: `Stop`
/// would stop the sheep.
#[tokio::test(start_paused = true)]
async fn reset_routes_to_the_supervisor_and_answers_reset() {
    let h = harness(vec![ProcScript::never_exits()]);
    start_web(&h).await;

    let reply = reply_of(
        dispatch(
            envelope(
                2,
                Request::Reset {
                    selector: SelectorSpec::Name("web".to_string()),
                },
            ),
            &h.ctx,
        )
        .await,
    );
    let Response::Reset(infos) = reply.result.unwrap() else {
        panic!("expected reset")
    };
    assert_eq!(infos.len(), 1);
    assert_eq!(infos[0].restarts, 0);

    let flock = list_flock(&h.ctx, 3).await;
    assert_eq!(
        flock[0].status,
        ProcStatus::Online,
        "a reset must not disturb the sheep it resets"
    );
}

/// Fails if the arm is routed to another verb's supervisor call while
/// keeping `Response::Reloading`, which no assertion on the reply alone can
/// see. What separates a reload is the flock it leaves behind: two entries
/// in one instance slot, the drainee `Stopping` under its original id and a
/// replacement `Starting` under a new one.
///
/// The mid-swap state is not a race: `ListFlock` is queued to an actor that runs `handle_reload` to completion.
#[tokio::test(start_paused = true)]
async fn reload_routes_to_the_supervisor_and_starts_a_swap() {
    let h = harness(vec![ProcScript::never_exits(); 3]);
    start_web(&h).await;

    let reply = reply_of(
        dispatch(
            envelope(
                2,
                Request::Reload {
                    selector: SelectorSpec::Name("web".to_string()),
                },
            ),
            &h.ctx,
        )
        .await,
    );
    let Response::Reloading { accepted, .. } = reply.result.unwrap() else {
        panic!("expected reloading")
    };
    assert_eq!(accepted.len(), 1);
    assert_eq!(
        accepted[0].status,
        ProcStatus::Online,
        "the answer is the flock as it stood when the reload was accepted"
    );

    let flock = list_flock(&h.ctx, 3).await;
    assert_eq!(
        flock.len(),
        2,
        "a swap in progress is two entries in one instance slot, not one: {flock:?}"
    );
    assert_eq!(flock[0].id, accepted[0].id);
    assert_eq!(flock[0].status, ProcStatus::Stopping);
    assert_ne!(
        flock[1].id, accepted[0].id,
        "the replacement takes a new id"
    );
    assert_eq!(flock[1].status, ProcStatus::Starting);
}
/// Fails if the `ReopenFailed | FlushFailed` arm answers any other code:
/// `SpawnFailed` exits 7 and reads as "could not start it". Fails too if
/// it sends the bare payload instead of `err.to_string()`, since once the
/// two share a wire code `Display` is all that tells a reader which half
/// of the log plane failed.
#[test]
fn a_log_plane_failure_is_internal_and_says_which_half_failed() {
    let reopen = rpc_error(&SupervisorError::ReopenFailed(
        "web (id 0): could not reopen /logs/web-out.log: Permission denied".to_string(),
    ));
    assert_eq!(reopen.code, RpcErrorCode::Internal);
    assert_eq!(
        reopen.message,
        "log reopen failed: web (id 0): could not reopen \
         /logs/web-out.log: Permission denied"
    );

    let flush = rpc_error(&SupervisorError::FlushFailed(
        "/logs/web-out.log: Permission denied".to_string(),
    ));
    assert_eq!(flush.code, RpcErrorCode::Internal);
    assert_eq!(
        flush.message,
        "log flush failed: /logs/web-out.log: Permission denied"
    );
}

#[tokio::test(start_paused = true)]
async fn subscribe_hands_back_a_compiled_filter() {
    let h = harness(vec![]);
    let outcome = dispatch(
        envelope(
            1,
            Request::Subscribe {
                topics: vec!["process.*".to_string()],
            },
        ),
        &h.ctx,
    )
    .await;
    let Outcome::Subscribe { reply, filter } = outcome else {
        panic!("expected subscribe")
    };
    assert_eq!(reply.result.unwrap(), Response::Subscribed);
    assert_eq!(filter.patterns(), ["process.*"]);

    let bad = reply_of(
        dispatch(
            envelope(
                2,
                Request::Subscribe {
                    topics: vec!["[".to_string()],
                },
            ),
            &h.ctx,
        )
        .await,
    );
    assert_eq!(bad.result.unwrap_err().code, RpcErrorCode::InvalidConfig);
}

#[tokio::test(start_paused = true)]
async fn kill_daemon_asks_for_shutdown_without_taking_the_engine_down_itself() {
    let mut h = harness(vec![]);
    let Outcome::Shutdown(reply) = dispatch(envelope(1, Request::KillDaemon), &h.ctx).await else {
        panic!("expected a shutdown outcome")
    };
    assert_eq!(reply.result.unwrap(), Response::ShuttingDown);
    // Dispatch only reports the intent; the connection layer triggers it.
    assert!(!*h.shutdown_rx.borrow_and_update());
    h.ctx.shutdown();
    assert!(h.shutdown_rx.changed().await.is_ok());
    assert!(*h.shutdown_rx.borrow());
}

#[test]
fn budgets_default_and_clamp() {
    assert_eq!(budget(None), Duration::from_millis(DEFAULT_DEADLINE_MS));
    assert_eq!(budget(Some(250)), Duration::from_millis(250));
    assert_eq!(budget(Some(0)), Duration::from_millis(1));
    assert_eq!(
        budget(Some(u64::MAX)),
        Duration::from_millis(MAX_DEADLINE_MS)
    );
}

#[tokio::test(start_paused = true)]
async fn envelope_deadline_ms_actually_bounds_the_reply() {
    // Drives a real envelope's `deadline_ms` through `dispatch` into
    // `budget`. `Stop` on an `ignores_signals()` sheep waits the full
    // 1600ms `kill_timeout` ladder, far past this 1ms deadline, while a
    // build passing `budget(None)` would take the 5s default and pass.
    let h = harness(vec![ProcScript::ignores_signals()]);
    start_web(&h).await;

    let reply = reply_of(
        dispatch(
            Envelope {
                id: 2,
                deadline_ms: Some(1),
                body: Request::Stop {
                    selector: SelectorSpec::Name("web".to_string()),
                },
            },
            &h.ctx,
        )
        .await,
    );
    let err = reply.result.unwrap_err();
    assert_eq!(
        err.code,
        RpcErrorCode::DeadlineExceeded,
        "a 1ms client deadline against a 1600ms kill ladder must expire, not {err:?}"
    );
}

#[tokio::test(start_paused = true)]
async fn work_past_its_deadline_answers_deadline_exceeded() {
    // Driven at the deadline seam with a future that never finishes: the
    // paused clock auto-advances the moment the test parks, so this is
    // instant and exact.
    let outcome = with_deadline(
        5,
        Duration::from_millis(250),
        std::future::pending::<Outcome>(),
    )
    .await;
    let reply = reply_of(outcome);
    assert_eq!(reply.id, 5);
    let err = reply.result.unwrap_err();
    assert_eq!(err.code, RpcErrorCode::DeadlineExceeded);
    assert!(err.message.contains("250 ms"), "{}", err.message);
}

/// The assertion reads the file the reply named and compares its app
/// count against the number the reply claimed, so a handler answering
/// `apps: 0` for a two-app flock reddens here.
#[tokio::test]
async fn save_roll_writes_the_file_it_names_and_counts_what_it_recorded() {
    let h = harness(vec![ProcScript::never_exits(), ProcScript::never_exits()]);
    reply_of(
        dispatch(
            envelope(
                1,
                Request::Start {
                    apps: vec![
                        AppConfig::minimal("web", "./srv"),
                        AppConfig::minimal("worker", "./work"),
                    ],
                },
            ),
            &h.ctx,
        )
        .await,
    );

    let reply = reply_of(dispatch(envelope(2, Request::SaveRoll), &h.ctx).await);
    let Ok(Response::RollSaved { path, apps }) = reply.result else {
        panic!("expected RollSaved, got {:?}", reply.result)
    };
    assert_eq!(apps, 2);

    let roll = crate::snapshot::read(std::path::Path::new(&path)).unwrap();
    assert_eq!(roll.apps.len(), 2, "the reply's count must match the file");
    assert_eq!(path, h.ctx.snapshot_path.display().to_string());
}

/// fails if the muster roll keeps the pre-scale count. This is the test for the
/// bug that is invisible until a reboot: the roll is what `shep muster` reads,
/// so a scale missing from it is a scale that silently reverts.
#[tokio::test]
async fn a_scale_is_recorded_in_the_roll_the_next_muster_reads() {
    let h = harness(vec![ProcScript::never_exits(); 4]);
    let mut app = AppConfig::minimal("web", "./srv");
    app.instances = 2;
    reply_of(dispatch(envelope(1, Request::Start { apps: vec![app] }), &h.ctx).await);

    reply_of(
        dispatch(
            envelope(
                2,
                Request::Scale {
                    name: "web".to_string(),
                    count: 4,
                },
            ),
            &h.ctx,
        )
        .await,
    );

    let reply = reply_of(dispatch(envelope(3, Request::SaveRoll), &h.ctx).await);
    let Ok(Response::RollSaved { path, .. }) = reply.result else {
        panic!("expected RollSaved, got {:?}", reply.result)
    };
    let roll = crate::snapshot::read(std::path::Path::new(&path)).unwrap();
    assert_eq!(roll.apps[0].app.instances, 4);
}

/// `web` at two instances, scaled to four, with one script left so the
/// first new spawn succeeds and the second fails. Three instances are then
/// running: a roll saying `2` stops one at the next muster, a roll saying
/// `4` brings up a count that never ran.
///
/// The reply is asserted as well as the roll: recording what the daemon did
/// must not turn "three of four" into a success.
#[tokio::test]
async fn a_partial_scale_is_recorded_in_the_roll_and_still_reported_short() {
    let h = harness(vec![ProcScript::never_exits(); 3]);
    let mut app = AppConfig::minimal("web", "./srv");
    app.instances = 2;
    reply_of(dispatch(envelope(1, Request::Start { apps: vec![app] }), &h.ctx).await);

    let reply = reply_of(
        dispatch(
            envelope(
                2,
                Request::Scale {
                    name: "web".to_string(),
                    count: 4,
                },
            ),
            &h.ctx,
        )
        .await,
    );
    let err = reply.result.unwrap_err();
    assert_eq!(err.code, RpcErrorCode::SpawnFailed);
    assert!(
        err.message.contains("3 of 4"),
        "the operator has to be told both numbers: {}",
        err.message
    );

    let saved = reply_of(dispatch(envelope(3, Request::SaveRoll), &h.ctx).await);
    let Ok(Response::RollSaved { path, .. }) = saved.result else {
        panic!("expected RollSaved, got {:?}", saved.result)
    };
    let roll = crate::snapshot::read(std::path::Path::new(&path)).unwrap();
    assert_eq!(
        roll.apps[0].app.instances, 3,
        "the roll must hold the three instances really running — not the \
         pre-scale two, and not the four that were asked for"
    );
}

/// Fails if the handler forwards `snapshot_now`'s engine-stopped `Ok(())`
/// as a success. A save that wrote nothing and said "saved" is the
/// failure mode an operator reboots into.
#[tokio::test]
async fn save_roll_against_a_stopped_engine_is_an_error_not_a_silent_success() {
    let h = harness(vec![]);
    h.ctx.supervisor.shutdown().await;

    let reply = reply_of(dispatch(envelope(1, Request::SaveRoll), &h.ctx).await);
    let err = reply.result.unwrap_err();
    assert_eq!(err.code, RpcErrorCode::Internal);
    assert!(
        err.message.contains("engine"),
        "the operator must be told why nothing was written: {}",
        err.message
    );
}

/// Assembling a flock that is already assembled starts nothing, so a reply
/// naming only what this call spawned cannot be told from "the roll was
/// empty".
///
/// One script: `web`'s first start consumes it, so a muster that started the
/// roll's apps unconditionally would exhaust the pool and land a second,
/// `Errored` `web` in the listing.
#[tokio::test]
async fn a_second_muster_still_reports_the_flock_the_roll_restored() {
    let h = harness(vec![ProcScript::never_exits()]);
    start_web(&h).await;
    reply_of(dispatch(envelope(2, Request::SaveRoll), &h.ctx).await);

    let reply = reply_of(dispatch(envelope(3, Request::Muster), &h.ctx).await);
    let Ok(Response::Mustered(infos)) = reply.result else {
        panic!("expected Mustered, got {:?}", reply.result)
    };
    assert_eq!(
        infos.len(),
        1,
        "the sheep the roll restores, not the ones this call spawned"
    );
    assert_eq!(infos[0].name, "web");
    assert_eq!(infos[0].status, ProcStatus::Online);
}