shep-daemon 0.25.2

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
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
//! One sheep's carried state: what the successor needs to keep a single
//! sheep alive across the exec.
//!
//! [`CarriedSheep`] is one row of the blob, holding both what the sheep is
//! and what it is currently doing. [`CarriedFds`] is the eight descriptor
//! numbers its output, input, shepherd channel, a pty sheep's terminal master
//! and, for a dog, its own connection travel on, and [`SheepFd`] says which of
//! the eight a number is, since the adoption path refuses a pipe and a log
//! handle by opposite checks.

use std::os::fd::RawFd;
use std::time::SystemTime;

use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use shep_core::config::AppConfig;
use shep_core::protocol::{DogSource, ExitInfo};
use shep_core::status::ProcStatus;

use crate::entry::{ProcessEntry, ReloadState};
use crate::privilege::SpawnIdentity;
use crate::supervisor::PendingManual;

/// Refuses the decode-only `Unrecognized` fallback in a blob.
///
/// A blob is read back into live supervisor state, which no code path
/// handles an unreadable status in: adopting one would leave a sheep that
/// `stop` silently ignores and that every client is sent as `"unrecognized"`.
/// Failing the load keeps the handover's rollback, as it did before the wire
/// enum grew a fallback.
fn known_status<'de, D: Deserializer<'de>>(deserializer: D) -> Result<ProcStatus, D::Error> {
    match ProcStatus::deserialize(deserializer)? {
        ProcStatus::Unrecognized => Err(D::Error::custom(
            "a carried sheep's status is not one this build knows",
        )),
        status => Ok(status),
    }
}

/// [`known_status`] for [`CarriedSheep::dog`]: an unreadable source would
/// lose the marker `shep dogs` and the dog watch read.
fn known_dog<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<DogSource>, D::Error> {
    match Option::<DogSource>::deserialize(deserializer)? {
        Some(DogSource::Unrecognized) => Err(D::Error::custom(
            "a carried dog's source is not one this build knows",
        )),
        source => Ok(source),
    }
}

/// One sheep, as the successor will find it.
///
/// [`Self::app`] is what the sheep is, carried whole so the successor can
/// respawn this exact instance without asking the muster roll. Every other
/// field is what this instance is currently doing.
///
/// An absent `Option` key loads as `None`, so a blob an older image wrote still loads.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedSheep {
    /// The supervisor's entry id, which callers already hold and selectors
    /// already name.
    pub(super) id: u32,
    /// The sheep's name, which is how an operator names it back.
    pub(super) name: String,
    /// The instance slot within its app.
    pub(super) instance: u32,
    /// The running process, or `None` for an instance that is registered and
    /// not running.
    pub(super) pid: Option<u32>,
    /// Respawns performed so far, which the restart budget counts against.
    pub(super) restarts: u32,
    /// The supervisor slot's respawn epoch, so a timer armed before the exec
    /// is still recognised as stale afterwards.
    pub(super) epoch: u64,
    /// The instance's lifecycle status.
    ///
    /// A status this build cannot read fails the load, see [`known_status`].
    #[serde(deserialize_with = "known_status")]
    pub(super) status: ProcStatus,
    /// How this instance most recently stopped existing, if it has.
    pub(super) last_exit: Option<ExitInfo>,
    /// The last spawn refusal, carried even when no process exists.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(super) spawn_failure: Option<String>,
    /// The identity this instance's next spawn runs under.
    ///
    /// Carried resolved, never re-derived: the value is pinned at the first
    /// spawn, so a later change to the passwd database cannot move a running
    /// app's identity underneath it.
    pub(super) credentials: SpawnIdentity,
    /// The descriptor numbers this instance's output travels on.
    pub(super) fds: CarriedFds,
    /// What the carried connection had said by the time the predecessor
    /// handed over, or `None` for an instance without one
    /// ([`CarriedFds::dog_link`]) and for one whose peer had not yet sent its
    /// `Hello`.
    ///
    /// `Some` is the topic patterns it had subscribed to, empty for none. The
    /// subscription lives in the predecessor's memory and dies at the exec.
    pub(super) dog_topics: Option<Vec<String>>,
    /// Whether an operator's `delete` targeted this instance before the
    /// exec. An absent key means "no".
    pub(super) pending_delete: Option<bool>,
    /// The manual command that owned this instance's next exit before the
    /// exec, and who asked for it. `None` is already this field's own word
    /// for "no command owns this exit", so an absent key needs no second
    /// state.
    pub(super) manual: Option<PendingManual>,
    /// Which half of a reload's swap this instance is, if either. An absent
    /// key means [`ReloadState::None`].
    ///
    /// It routes this instance's next exit: without it a drainee's exit goes
    /// to `decide_on_exit`, and an `autorestart` app respawns the old code
    /// into the replacement's slot.
    pub(super) reload: Option<ReloadState>,
    /// Whether a reload's readiness verification has already failed against
    /// this instance. An absent key reads as `false`.
    ///
    /// It keeps a failed reload's leftovers reachable: an abandoned instance
    /// is left `Starting`, and `reload_eligible` reads this flag beside the
    /// status so a rollback can still reach it.
    pub(super) ready_failed: Option<bool>,
    /// When this instance's owed respawn falls due, in wall-clock terms, or
    /// `None` for an instance that is not owed one at all.
    ///
    /// Wall-clock and not monotonic: a [`tokio::time::Instant`] has no epoch
    /// across the `execve`, while an absolute moment lets the successor re-arm
    /// for what is left. A clock that moves under it is clamped by
    /// [`adopted_restart_delay`](crate::backoff::adopted_restart_delay).
    pub(super) restart_due: Option<SystemTime>,
    /// Where this instance's binary came from, for an instance that is a
    /// dog, or `None` for an ordinary sheep.
    ///
    /// An absent key means "not a dog". The whole [`DogSource`] and not a
    /// boolean, because `shep dogs` reports where each dog's binary came from.
    ///
    /// Losing the marker is invisible to a pid check.
    #[serde(default, deserialize_with = "known_dog")]
    pub(super) dog: Option<DogSource>,
    /// The config a load parked for this instance's next spawn, or `None`
    /// for an instance nothing is owed.
    ///
    /// An `AppConfig` and not a `ResolvedApp` for the reason [`Self::app`]
    /// gives. Losing it is silent config erasure: the parked change vanishes
    /// and the next load compares against a spec that already matched.
    pub(super) pending: Option<AppConfig>,
    /// Whether promoting [`Self::pending`] must re-resolve
    /// [`Self::credentials`].
    ///
    /// `None` reads as `false`, and covers both an absent key and a sheep with
    /// nothing parked. Carried with [`Self::pending`] and never without it: the
    /// load that parks the config decides this, and a later diff cannot
    /// recompute it.
    pub(super) pending_reidentifies: Option<bool>,
    /// Whether an operator disabled this instance's app. An absent key reads
    /// as "no".
    ///
    /// The mark belongs to the app, so every instance of a disabled app
    /// carries it. Without it the successor starts with nothing disabled and
    /// its first roll write erases the mark from disk.
    pub(super) disabled: Option<bool>,
    /// The resolved config this instance runs under, environment included.
    ///
    /// The `AppConfig` beneath [`ProcessEntry::spec`]'s `ResolvedApp`, not the
    /// `ResolvedApp` itself: that type is a proof token minted only by
    /// `normalize`, so the successor rebuilds it by normalizing again. A
    /// successor whose `normalize` has tightened refuses a config its
    /// predecessor accepted, with no stop arm left.
    pub(super) app: AppConfig,
}

impl CarriedSheep {
    /// Describe `entry` for the successor.
    ///
    /// The arguments beyond `entry` do not live on it. `restart_due` is the
    /// one not carried verbatim: it is gated on the entry's status.
    #[must_use]
    pub fn from_entry(
        entry: &ProcessEntry,
        epoch: u64,
        fds: CarriedFds,
        pending_delete: bool,
        manual: Option<PendingManual>,
        ready_failed: bool,
        restart_due: Option<SystemTime>,
    ) -> Self {
        Self {
            id: entry.id,
            name: entry.spec.config().name.clone(),
            instance: entry.instance,
            pid: entry.pid,
            restarts: entry.restarts,
            epoch,
            status: entry.status,
            last_exit: entry.last_exit,
            spawn_failure: entry.spawn_failure.clone(),
            credentials: entry.credentials,
            fds,
            dog_topics: None,
            pending_delete: Some(pending_delete),
            manual,
            reload: Some(entry.reload),
            dog: entry.dog.clone(),
            // Written as a pair with the flag below: a config without its
            // flag promotes on the wrong identity.
            pending: entry.pending.as_ref().map(|parked| parked.config().clone()),
            // Same `Option` as the line above, so the two keys are absent
            // together.
            pending_reidentifies: entry.pending.as_ref().map(|_| entry.pending_reidentifies),
            ready_failed: Some(ready_failed),
            // The slot's own field is written on the one transition into
            // `WaitingRestart` and never cleared, so gating here stops an
            // expired moment riding out on an `Online` row.
            restart_due: (entry.status == ProcStatus::WaitingRestart)
                .then_some(restart_due)
                .flatten(),
            disabled: None,
            app: entry.spec.config().clone(),
        }
    }

    /// This row, carrying whether its app is disabled.
    ///
    /// Separate from [`Self::from_entry`] because the mark lives on the
    /// supervisor's app set and not on the entry.
    #[must_use]
    pub fn with_disabled(mut self, disabled: bool) -> Self {
        self.disabled = Some(disabled);
        self
    }

    /// Has this row carry its connection: the dog's own, or the launch link
    /// of a sheep sandboxed by a dog.
    ///
    /// Separate from [`Self::from_entry`] because the connection is held by
    /// the server that serves it and not by the log pump `fds` is reported
    /// from. `topics` is what the connection had subscribed to, or `None` if
    /// the dog had not yet sent its `Hello`.
    pub(super) fn carry_dog_link(&mut self, fd: RawFd, topics: Option<Vec<String>>) {
        self.fds.dog_link = Some(fd);
        self.dog_topics = topics;
    }

    /// The descriptor numbers this instance's output travels on.
    #[must_use]
    #[allow(dead_code, reason = "read by this crate's own tests")]
    pub const fn fds(&self) -> CarriedFds {
        self.fds
    }

    /// The topic patterns this dog's carried connection had subscribed to, or
    /// `None` for a connection whose dog had not yet said `Hello`.
    #[must_use]
    pub fn dog_topics(&self) -> Option<&[String]> {
        self.dog_topics.as_deref()
    }

    /// Whether an operator's `delete` targeted this instance before the
    /// exec, or `None`, which means "no".
    #[must_use]
    pub const fn pending_delete(&self) -> Option<bool> {
        self.pending_delete
    }

    /// The manual command that owned this instance's next exit before the
    /// exec, or `None` for an instance no command was waiting on.
    #[must_use]
    pub const fn manual(&self) -> Option<PendingManual> {
        self.manual
    }

    /// Which half of a reload's swap this instance is, or `None`, which
    /// means [`ReloadState::None`].
    #[must_use]
    pub const fn reload(&self) -> Option<ReloadState> {
        self.reload
    }

    /// Where this instance's binary came from if it is a dog, or `None` for
    /// an ordinary sheep.
    ///
    /// Borrowed rather than cloned: [`DogSource::Adopted`] owns a path.
    #[must_use]
    pub const fn dog(&self) -> Option<&DogSource> {
        self.dog.as_ref()
    }

    /// The config a load parked for this instance's next spawn, or `None`
    /// for an instance nothing is owed.
    #[must_use]
    pub const fn pending(&self) -> Option<&AppConfig> {
        self.pending.as_ref()
    }

    /// Whether promoting [`Self::pending`] must re-resolve the identity, or
    /// `None`, which reads as `false`.
    #[must_use]
    pub const fn pending_reidentifies(&self) -> Option<bool> {
        self.pending_reidentifies
    }

    /// Whether a reload's readiness verification has already failed against
    /// this instance, or `None`, which reads as `false`.
    #[must_use]
    pub const fn ready_failed(&self) -> Option<bool> {
        self.ready_failed
    }

    /// Whether an operator disabled this instance's app, or `None`, which
    /// means "no".
    #[must_use]
    pub const fn disabled(&self) -> Option<bool> {
        self.disabled
    }

    /// When this instance's owed respawn falls due, or `None` for one that is
    /// not owed a respawn.
    #[must_use]
    pub const fn restart_due(&self) -> Option<SystemTime> {
        self.restart_due
    }

    /// The supervisor slot's respawn epoch at the moment of the handover.
    #[must_use]
    pub const fn epoch(&self) -> u64 {
        self.epoch
    }

    /// The entry id this instance keeps across the handover.
    #[must_use]
    pub const fn id(&self) -> u32 {
        self.id
    }

    /// The name an operator reaches this instance by.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The instance slot within its app.
    #[must_use]
    pub const fn instance(&self) -> u32 {
        self.instance
    }

    /// The pid this instance is running under, or `None` for one that is
    /// registered and not running.
    ///
    /// An instance with no pid has [`CarriedFds::none`] and nothing to adopt.
    #[must_use]
    pub const fn pid(&self) -> Option<u32> {
        self.pid
    }

    /// Respawns performed so far, which the restart budget counts against.
    #[must_use]
    pub const fn restarts(&self) -> u32 {
        self.restarts
    }

    /// The instance's lifecycle status.
    #[must_use]
    pub const fn status(&self) -> ProcStatus {
        self.status
    }

    /// How this instance most recently stopped existing, if it has.
    #[must_use]
    pub const fn last_exit(&self) -> Option<ExitInfo> {
        self.last_exit
    }

    /// The last spawn refusal, without environment values.
    pub fn spawn_failure(&self) -> Option<&str> {
        self.spawn_failure.as_deref()
    }

    /// The identity this instance's next spawn runs under, resolved once by
    /// the predecessor.
    #[must_use]
    pub const fn credentials(&self) -> SpawnIdentity {
        self.credentials
    }

    /// The config this instance runs under, as its predecessor normalized it.
    ///
    /// Not a [`ResolvedApp`](shep_core::config::ResolvedApp): see the field's
    /// own doc.
    #[must_use]
    pub const fn app(&self) -> &AppConfig {
        &self.app
    }
}

/// The shepherd's end of one dog's own connection, held for the exec.
///
/// Owns a duplicate of the descriptor the server task is reading, so the
/// number [`Handover::carry_dog_links`](super::Handover::carry_dog_links)
/// writes into the blob cannot name a different file if that task ends first.
///
/// `Debug` is derived: no env value reaches this type.
#[derive(Debug)]
pub struct DogConnection {
    /// The dog's name, as its sheep is named.
    pub name: String,
    /// The sheep a launch link was opened for, which the connection is carried
    /// on; `None` for a dog's own, carried on the dog.
    pub launch_for: Option<String>,
    /// The pid the dog was spawned under, which tells an instance that has
    /// since respawned from the one this connection belongs to.
    pub pid: u32,
    /// The duplicate to carry.
    pub fd: std::os::fd::OwnedFd,
    /// What the dog had subscribed to, or `None` if it had not yet said
    /// `Hello`; see [`CarriedSheep::dog_topics`].
    pub topics: Option<Vec<String>>,
}

/// One of a sheep's bound `listen` sockets, as the blob names it.
///
/// Keyed by the sheep's name and the entry's name in its `listen` table, since
/// the sockets belong to the app and not to one instance. Not part of
/// [`CarriedFds`]: the successor replaces a bad one, where it refuses a bad
/// number there. `Debug` is derived: no env value reaches this type.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedListener {
    /// The sheep whose `listen` table holds the entry.
    pub(super) sheep: String,
    /// The entry's name in that table.
    pub(super) name: String,
    /// The address the table binds, as the shepherd parsed it, which is what
    /// a later reload matches an address on.
    pub(super) address: String,
    /// The descriptor number the listening socket travels on.
    pub(super) fd: RawFd,
    /// Set by [`claim`](super::claim) when the socket did not arrive under
    /// `fd`, so that number is not this socket's to adopt.
    ///
    /// Never written to a blob: it describes an arrival, not a predecessor.
    #[serde(skip)]
    pub(super) unclaimed: bool,
}

impl CarriedListener {
    /// The sheep whose `listen` table holds the entry.
    #[must_use]
    pub fn sheep(&self) -> &str {
        &self.sheep
    }

    /// The entry's name in the sheep's `listen` table.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The address the entry binds, as the shepherd parsed it.
    #[must_use]
    pub fn address(&self) -> &str {
        &self.address
    }

    /// The descriptor number the socket travels on.
    #[must_use]
    pub const fn fd(&self) -> RawFd {
        self.fd
    }

    /// Whether the socket failed to arrive under [`Self::fd`], which then
    /// names nothing the successor may take.
    #[must_use]
    pub const fn unclaimed(&self) -> bool {
        self.unclaimed
    }
}

/// The shepherd's end of one `listen` socket, held for the exec.
///
/// Owns a duplicate of the socket, so the number
/// [`Handover::carry_listeners`](super::Handover::carry_listeners) writes into
/// the blob stays open if the supervisor drops its set first. `Debug` is
/// derived: no env value reaches this type.
#[derive(Debug)]
pub struct HeldListener {
    /// The sheep whose `listen` table holds the entry.
    pub sheep: String,
    /// The entry's name in that table.
    pub name: String,
    /// The address the entry binds, as the shepherd parsed it.
    pub address: String,
    /// The duplicate to carry.
    pub fd: std::os::fd::OwnedFd,
}

/// The descriptor numbers one sheep's output travels on, the one its input
/// travels back through, the one carrying both directions of its shepherd
/// channel, and for a dog the one carrying its own connection.
///
/// `None` on the four output fields means the instance is registered and not
/// running; losing a sheep's stdout read end blocks the child on `write()`
/// once the 64KiB pipe buffer fills.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct CarriedFds {
    /// The read end of the sheep's stdout pipe.
    pub out_pipe: Option<RawFd>,
    /// The read end of the sheep's stderr pipe.
    pub err_pipe: Option<RawFd>,
    /// The appending handle on the sheep's stdout log file.
    pub out_log: Option<RawFd>,
    /// The appending handle on the sheep's stderr log file.
    pub err_log: Option<RawFd>,
    /// The write end of the sheep's stdin pipe, which `shep whisper` writes
    /// a line into.
    ///
    /// `None` for a sheep whose app did not set `stdin = true`, which has
    /// `/dev/null` on fd 0, and for a sheep that is not running. An absent
    /// field loads as `None`, so [`VERSION`](super::VERSION) is unmoved.
    pub stdin: Option<RawFd>,
    /// The daemon's end of the sheep's shepherd-channel socketpair, whose
    /// other end is the child's fd 3. One number for both directions:
    /// `spawn_channel_pumps` splits it into two tasks over one open file
    /// description.
    ///
    /// `None` for a sheep whose app set none of `channel`, `wait_ready` or
    /// `shutdown_with_message`, and for one that is not running.
    pub channel: Option<RawFd>,
    /// The daemon's end of the child's fd 4: a dog's own connection, or a
    /// launched sheep's launch link.
    ///
    /// One number for both directions, served by the same task that served it
    /// before the exec. `None` for a sheep with neither, for a dog
    /// that is not running, and for one whose connection had already closed.
    /// An absent field loads as `None`.
    pub dog_link: Option<RawFd>,
    /// The master side of a pty sheep's pseudo-terminal, which the child has
    /// as its stdio.
    ///
    /// `None` for a sheep that runs on pipes and for one that is not running.
    /// An absent field loads as `None`, so [`VERSION`](super::VERSION) is
    /// unmoved.
    pub pty: Option<RawFd>,
}

/// Which of a sheep's eight descriptors a number is. A stdout pipe and a stdin
/// pipe are both pipes and are refused by opposite checks, so the slot has to
/// travel with the number.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum SheepFd {
    /// The read end of the sheep's stdout pipe ([`CarriedFds::out_pipe`]).
    OutPipe,
    /// The read end of the sheep's stderr pipe ([`CarriedFds::err_pipe`]).
    ErrPipe,
    /// The appending handle on its stdout log ([`CarriedFds::out_log`]).
    OutLog,
    /// The appending handle on its stderr log ([`CarriedFds::err_log`]).
    ErrLog,
    /// The write end of its stdin pipe ([`CarriedFds::stdin`]).
    Stdin,
    /// The daemon's end of its shepherd channel ([`CarriedFds::channel`]).
    Channel,
    /// The daemon's end of the dog's own connection ([`CarriedFds::dog_link`]).
    DogLink,
    /// The master side of its pseudo-terminal ([`CarriedFds::pty`]).
    Pty,
}

impl SheepFd {
    /// What this slot is called in a refusal. Must match the wording the
    /// adoption functions use.
    pub(crate) const fn describe(self) -> &'static str {
        match self {
            Self::OutPipe => "stdout pipe",
            Self::ErrPipe => "stderr pipe",
            Self::OutLog => "stdout log",
            Self::ErrLog => "stderr log",
            Self::Stdin => "stdin pipe",
            Self::Channel => "shepherd channel",
            Self::DogLink => "dog connection",
            Self::Pty => "pty master",
        }
    }
}

impl CarriedFds {
    /// The eight numbers in a fixed order: stdout's pipe, stderr's pipe,
    /// stdout's log, stderr's log, stdin's pipe, the shepherd channel, the
    /// dog's connection, the pty master.
    #[must_use]
    pub const fn all(&self) -> [Option<RawFd>; 8] {
        [
            self.out_pipe,
            self.err_pipe,
            self.out_log,
            self.err_log,
            self.stdin,
            self.channel,
            self.dog_link,
            self.pty,
        ]
    }

    /// [`Self::all`], with each number labelled by which of the eight it is.
    ///
    /// [`adopt`](super::adopt::adopt) and [`dry_run`](super::adopt::dry_run)
    /// must agree on the kinds: a number rehearsed as the wrong kind is a
    /// rehearsal that passes and a boot that still fails.
    pub(crate) const fn all_kinded(&self) -> [(Option<RawFd>, SheepFd); 8] {
        [
            (self.out_pipe, SheepFd::OutPipe),
            (self.err_pipe, SheepFd::ErrPipe),
            (self.out_log, SheepFd::OutLog),
            (self.err_log, SheepFd::ErrLog),
            (self.stdin, SheepFd::Stdin),
            (self.channel, SheepFd::Channel),
            (self.dog_link, SheepFd::DogLink),
            (self.pty, SheepFd::Pty),
        ]
    }

    /// The no-descriptors case: a sheep that is registered and not running.
    /// [`fitness`](fn@super::fitness) does not refuse it.
    #[must_use]
    pub const fn none() -> Self {
        Self {
            out_pipe: None,
            err_pipe: None,
            out_log: None,
            err_log: None,
            stdin: None,
            channel: None,
            dog_link: None,
            pty: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{CarriedFds, CarriedSheep, SheepFd};
    use crate::entry::ReloadState;
    use crate::handover::adopt::dry_run;
    use crate::handover::fixtures::{carried, entry_fixture, fds_at, plain};
    use crate::handover::{Counters, DaemonFds, Fitness, Handover, fitness};
    use crate::supervisor::{CommandOrigin, ManualKind, PendingManual};

    /// [`CarriedSheep::instance`] is carried per row rather than re-derived
    /// from a count: without that, two live pids write into each other's log
    /// files under each other's `SHEP_INSTANCE`.
    #[test]
    fn each_instance_carries_its_own_slot_and_descriptors() {
        let mut zero = entry_fixture(|app| app.instances = 2);
        zero.instance = 0;
        let mut one = entry_fixture(|app| app.instances = 2);
        one.id = 2;
        one.instance = 1;
        one.pid = Some(101);

        let blob = Handover::new(
            vec![
                CarriedSheep::from_entry(&zero, 7, fds_at(11), false, None, false, None),
                CarriedSheep::from_entry(&one, 8, fds_at(21), false, None, false, None),
            ],
            DaemonFds {
                listener: 3,
                pidfile: 4,
            },
            Counters {
                next_id: 9,
                next_deadline: 5,
                next_action_stamp: 2,
            },
            Vec::new(),
        );
        let back: Handover = serde_json::from_str(&serde_json::to_string(&blob).unwrap()).unwrap();

        let carried = back.sheep();
        assert_eq!(carried.len(), 2, "one row per instance, never per app");
        // Bound by slot rather than by position, so a reordered blob still
        // has to put each pid with its own slot.
        let slot_zero = carried
            .iter()
            .find(|sheep| sheep.instance() == 0)
            .expect("slot 0 must be carried");
        let slot_one = carried
            .iter()
            .find(|sheep| sheep.instance() == 1)
            .expect("slot 1 must be carried");
        assert_eq!(slot_zero.id(), 1);
        assert_eq!(slot_zero.pid(), Some(100));
        assert_eq!(slot_zero.epoch(), 7);
        assert_eq!(slot_zero.fds(), fds_at(11));
        assert_eq!(slot_one.id(), 2);
        assert_eq!(slot_one.pid(), Some(101));
        assert_eq!(slot_one.epoch(), 8);
        assert_eq!(slot_one.fds(), fds_at(21));
        assert_eq!(
            slot_zero.name(),
            slot_one.name(),
            "both slots are the same app, which is what makes the slot the \
             only thing telling them apart"
        );
    }

    /// Both halves of the swap, and the drainee's linked id with them.
    #[test]
    fn a_swap_in_flight_no_longer_refuses_and_reaches_the_blob() {
        let mut drainee = entry_fixture(|_| {});
        drainee.reload = ReloadState::Drainee { new_id: Some(9) };
        let mut replacement = entry_fixture(|_| {});
        replacement.id = 9;
        replacement.reload = ReloadState::Replacement;
        assert_eq!(
            fitness(&[plain(&drainee), plain(&replacement)]),
            Fitness::Carryable
        );

        assert_eq!(
            carried(&drainee).reload(),
            Some(ReloadState::Drainee { new_id: Some(9) }),
            "the id linking the two halves must survive the blob, not just the role"
        );
        assert_eq!(
            carried(&replacement).reload(),
            Some(ReloadState::Replacement)
        );
    }

    /// `Candidate` has nothing to say about a pending command, so this
    /// asserts through the blob rather than through the gate.
    #[test]
    fn a_pending_manual_command_no_longer_refuses_and_reaches_the_blob() {
        let e = entry_fixture(|_| {});
        assert_eq!(fitness(&[plain(&e)]), Fitness::Carryable);

        let marked = CarriedSheep::from_entry(
            &e,
            7,
            fds_at(11),
            false,
            Some(PendingManual {
                kind: ManualKind::Delete,
                origin: CommandOrigin::Automatic,
            }),
            false,
            None,
        );
        assert_eq!(
            marked.manual(),
            Some(PendingManual {
                kind: ManualKind::Delete,
                origin: CommandOrigin::Automatic,
            }),
            "both halves of the marker must survive the blob, not just that one exists"
        );
    }

    /// Eight distinct numbers, so the equality below is about the pairing
    /// rather than the length.
    #[test]
    fn every_carried_number_is_kinded_in_the_same_order() {
        let fds = CarriedFds {
            out_pipe: Some(10),
            err_pipe: Some(11),
            out_log: Some(12),
            err_log: Some(13),
            stdin: Some(14),
            channel: Some(15),
            dog_link: Some(16),
            pty: Some(17),
        };

        assert_eq!(
            fds.all_kinded().map(|(fd, _)| fd),
            fds.all(),
            "the kinded walk and the `FD_CLOEXEC` walk must see the same numbers"
        );

        let slots: std::collections::HashSet<SheepFd> =
            fds.all_kinded().iter().map(|(_, slot)| *slot).collect();
        assert_eq!(slots.len(), 8, "each slot must appear exactly once");
    }

    /// The master travels in the blob like any other number, so a successor
    /// reading it back finds the same descriptor.
    #[test]
    fn a_blob_round_trips_a_pty_descriptor() {
        let mut blob = sample_blob();
        blob.sheep[0].fds.pty = Some(40);

        let back: Handover = serde_json::from_str(&serde_json::to_string(&blob).unwrap()).unwrap();

        assert_eq!(back.sheep()[0].fds().pty, Some(40));
        assert_eq!(back, blob);
    }

    /// An absent key is what every earlier release wrote, so
    /// [`VERSION`](crate::handover::VERSION) is unmoved.
    #[test]
    fn a_blob_without_a_pty_key_loads_as_none() {
        let mut blob = sample_blob();
        blob.sheep[0].fds.pty = Some(40);
        let mut value = serde_json::to_value(&blob).unwrap();
        let fds = value["sheep"][0]["fds"]
            .as_object_mut()
            .expect("a carried sheep names its descriptors");
        assert!(
            fds.remove("pty").is_some(),
            "the key this case removes must be there to remove"
        );

        let loaded = Handover::load_value(value).expect("an older blob must still load");

        assert_eq!(loaded.sheep()[0].fds().pty, None);
        assert_eq!(
            loaded.sheep()[0].fds().out_pipe,
            blob.sheep()[0].fds().out_pipe,
            "the other descriptors are unchanged by the one that was absent"
        );
    }

    /// Two owners of one number close it twice, so the walk the repeat check
    /// reads must include the master.
    #[test]
    fn a_pty_master_named_twice_is_refused() {
        let mut blob = sample_blob();
        let fds = &mut blob.sheep[0].fds;
        fds.pty = fds.out_pipe;

        let err = dry_run(&blob).expect_err("one number cannot have two owners");

        assert!(
            err.to_string().contains("more than once"),
            "the refusal must be the repeat check's own: {err}"
        );
    }

    fn sample_blob() -> Handover {
        Handover::new(
            vec![carried(&entry_fixture(|_| {}))],
            DaemonFds {
                listener: 3,
                pidfile: 4,
            },
            Counters {
                next_id: 9,
                next_deadline: 5,
                next_action_stamp: 2,
            },
            Vec::new(),
        )
    }
}