shep_core/protocol/request.rs
1//! RPC frames: requests, responses, envelopes, and structured errors
2
3use core::fmt;
4
5use serde::{Deserialize, Deserializer, Serialize};
6
7use crate::config::AppConfig;
8use crate::status::ProcStatus;
9
10/// Client's opening frame
11// wire format: changing this is a breaking change
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct Hello {
14 /// Client crate version (semver string)
15 pub client_version: String,
16 /// [`crate::protocol::PROTOCOL_VERSION`] the client speaks
17 pub protocol: u32,
18 /// The name this client was registered under as a dog, when it is one.
19 ///
20 /// `None` is what every other client truthfully is, and what a dog built
21 /// before this field existed sends. The CLI never sets it: a bare
22 /// `Client` has no way to, by construction, so `shep stop` cannot
23 /// impersonate a dog however its environment is set.
24 ///
25 /// The daemon needs it on exactly one path, and it is the path where
26 /// nothing else can supply it. A handshake refused for protocol skew
27 /// never reaches a request, so `Request::DogConfig`'s name — the one
28 /// place a dog otherwise identifies itself — is unreachable precisely
29 /// when the daemon has to know WHICH dog it just refused in order to
30 /// restart it (the handover design's G8). A dog already knows its own
31 /// name: the daemon put it in `$SHEP_DOG_NAME` when it spawned it.
32 ///
33 /// Additive by construction: absent on the wire rather than `null`, and
34 /// ignored by a daemon too old to know it, so
35 /// [`crate::protocol::PROTOCOL_VERSION`] does not move for it. That
36 /// argument deserves more care here than anywhere else, because `Hello`
37 /// IS the version-negotiation frame: a daemon that rejected unknown
38 /// fields would refuse a newer client BEFORE reading `protocol`, and
39 /// that would be a hard break rather than an additive change. It does
40 /// not — this type carries no `#[serde(deny_unknown_fields)]`, and
41 /// `a_hello_without_a_dog_name_still_parses` pins both directions.
42 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub dog_name: Option<String>,
44}
45
46/// Daemon's handshake answer
47// wire format: changing this is a breaking change
48#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct HelloAck {
50 /// Daemon crate version
51 pub daemon_version: String,
52 /// Protocol version the daemon speaks
53 pub protocol: u32,
54 /// Daemon pid
55 pub pid: u32,
56}
57
58/// Serializable selector (mirror of [`crate::selector::ProcessSelector`];
59/// regex travels as its source string)
60// wire format: changing this is a breaking change
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
63pub enum SelectorSpec {
64 /// Every sheep
65 All,
66 /// By id
67 Id(u32),
68 /// By exact name
69 Name(String),
70 /// By regex source
71 Regex(String),
72 /// By fold name
73 Fold(String),
74 // Both field names are part of the wire contract, and the byte shape is
75 // pinned by `request_wire_v2`, so renaming either breaks that snapshot
76 // rather than sliding through unnoticed.
77 /// By app name and instance slot
78 ///
79 /// Added in protocol 2, and the reason that version exists: a daemon
80 /// built against protocol 1 has no such variant and refuses a client
81 /// that sends one at the handshake, rather than failing to decode it
82 /// later. On the wire this is `{"kind":"instance","value":{"name":
83 /// "web","slot":2}}`, following the enum's own `kind`/`value` tagging.
84 Instance {
85 /// The app name
86 name: String,
87 /// The instance slot, counting from 0
88 slot: u32,
89 },
90}
91
92/// A short marker a dog attaches to a sheep for `shep flock` to paint.
93///
94/// shep stores one and prints it. It does not parse it, has no opinion about
95/// what it means, and never will: `▲ main@a1b2c3` is a deploy tool's
96/// sentence, not shep's, and keeping it that way is what makes this a general
97/// mechanism rather than one feature's field.
98///
99/// # The rule
100///
101/// A smit is non-empty once whitespace is discounted, at most
102/// [`Self::MAX_CHARS`] characters, and carries no [`char::is_control`]
103/// character — `\u{1b}` included, which `is_control` already covers and which
104/// is named separately in this doc anyway, because it is the one an attacker
105/// reaches for and a reader should not have to know the classification to see
106/// that it is handled.
107///
108/// Refused, never repaired. The text is stored exactly as it arrived: shep
109/// does not trim it, strip from it, or otherwise hand back something the
110/// publisher did not send. `crate::kv`'s key grammar and value cap set the
111/// same precedent for the same kind of value, and the publisher here is a
112/// program, so a refusal it can see and fix beats mangling it cannot.
113///
114/// # Why the cap counts characters
115///
116/// [`Self::MAX_CHARS`] is a count of `char`s, not of bytes and not of display
117/// columns. Bytes would refuse a legitimate CJK smit at roughly a third of
118/// its apparent length. Display columns are what a table renderer measures,
119/// but they depend on the terminal and on a width table this parser has no
120/// business carrying. Characters are the honest thing a validator can promise
121/// cheaply. 48 is measured against the reference smit `▲ main@a1b2c3` at
122/// thirteen: room for a long branch name, without letting one column swallow
123/// the table.
124///
125/// # Why validation lives here rather than at the renderer
126///
127/// `shep`'s own `output::width::sanitize_cell` deliberately KEEPS a
128/// well-formed CSI sequence, because shep's colouring is made of them, so it
129/// is not a guard against a third party's string. Refusing here means `shep
130/// flock`, `shep describe`, `--format json`, the lookout, the MCP tool schema
131/// and every bus subscriber are safe by construction instead of six places
132/// each remembering.
133///
134/// `Debug` is derived, and that is the deliberate decision (IR-41): a smit
135/// carries no environment and no secret. It is a string a dog asked to have
136/// painted in public, so redacting it would hide the thing an operator is
137/// debugging.
138///
139/// # Example
140/// ```
141/// use shep_core::protocol::Smit;
142///
143/// assert_eq!("▲ main@a1b2c3".parse::<Smit>()?.as_str(), "▲ main@a1b2c3");
144/// assert!("\u{1b}[2Jgone".parse::<Smit>().is_err()); // no escapes
145/// # Ok::<(), shep_core::protocol::SmitError>(())
146/// ```
147// wire format: changing this is a breaking change
148#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
149pub struct Smit(String);
150
151impl Smit {
152 /// The longest a smit may be, in characters. See the type doc for why
153 /// characters rather than bytes or display columns.
154 pub const MAX_CHARS: usize = 48;
155
156 /// The marker as text, exactly as its publisher sent it.
157 #[must_use]
158 pub fn as_str(&self) -> &str {
159 &self.0
160 }
161}
162
163impl fmt::Display for Smit {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 f.write_str(&self.0)
166 }
167}
168
169impl core::str::FromStr for Smit {
170 type Err = SmitError;
171
172 /// # Errors
173 /// - [`SmitError::Empty`] — nothing but whitespace.
174 /// - [`SmitError::TooLong`] — over [`Self::MAX_CHARS`] characters.
175 /// - [`SmitError::Unprintable`] — a control character, `\u{1b}` included.
176 fn from_str(text: &str) -> Result<Self, Self::Err> {
177 if text.trim().is_empty() {
178 return Err(SmitError::Empty);
179 }
180 let chars = text.chars().count();
181 if chars > Self::MAX_CHARS {
182 return Err(SmitError::TooLong { chars });
183 }
184 if text.chars().any(char::is_control) {
185 return Err(SmitError::Unprintable);
186 }
187 Ok(Self(text.to_string()))
188 }
189}
190
191/// Hand-written rather than derived, and that is the whole security property.
192///
193/// A derived impl would accept anything a `String` accepts, so a smit
194/// carrying `\u{1b}[2J` would reach the daemon's memory and every listing
195/// built from it. `docs/dogs.md` tells dog authors to speak this wire
196/// directly, so a dog written in another language never runs
197/// [`core::str::FromStr`] — the daemon has to validate what it decodes, not
198/// trust that it was constructed properly.
199impl<'de> Deserialize<'de> for Smit {
200 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
201 // String, not &str: a non-borrowing deserializer cannot always borrow
202 let text = String::deserialize(deserializer)?;
203 text.parse().map_err(serde::de::Error::custom)
204 }
205}
206
207/// Why a string is not a [`Smit`].
208///
209/// `#[non_exhaustive]`: shep-core is a published library and a further
210/// refusal — a grapheme-cluster cap, say, or a bidi-override rule — must not
211/// break an out-of-tree consumer's `match` (IR-20).
212#[non_exhaustive]
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214pub enum SmitError {
215 /// Over [`Smit::MAX_CHARS`] characters; carries the count that was sent.
216 TooLong {
217 /// How many characters the string held.
218 chars: usize,
219 },
220 /// A control character, `\u{1b}` included — the sequence that would let a
221 /// third party's string drive an operator's terminal.
222 Unprintable,
223 /// Empty, or nothing but whitespace.
224 Empty,
225}
226
227impl fmt::Display for SmitError {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 match self {
230 Self::TooLong { chars } => write!(
231 f,
232 "a smit is at most {} characters; this one is {chars}",
233 Smit::MAX_CHARS
234 ),
235 Self::Unprintable => {
236 f.write_str("a smit may not contain a control character, an escape included")
237 }
238 Self::Empty => f.write_str("a smit may not be empty"),
239 }
240 }
241}
242
243impl core::error::Error for SmitError {}
244
245/// One RPC request
246// wire format: changing existing variants is a breaking change
247#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
248#[serde(tag = "kind", rename_all = "snake_case")]
249#[non_exhaustive]
250pub enum Request {
251 /// Liveness check
252 Ping,
253 /// Full flock listing
254 ListFlock,
255 /// Detailed info for matching sheep
256 Describe {
257 /// Which sheep
258 selector: SelectorSpec,
259 },
260 /// Register + start apps
261 Start {
262 /// App configs — the daemon MUST re-normalize (peer input is
263 /// untrusted); failures return [`RpcErrorCode::InvalidConfig`]
264 apps: Vec<AppConfig>,
265 },
266 /// Ask which of `apps` name a sheep the flock already has under a
267 /// different config
268 ///
269 /// Read-only: nothing is registered, started, or changed. [`Self::Start`]
270 /// on an already-registered name adds instances rather than reconciling
271 /// config, which is what `shep stock` relies on; this is how a caller
272 /// finds out that an edit it just read from a Flockfile is one `Start`
273 /// will not apply, instead of the edit vanishing without a word.
274 ///
275 /// Answers [`Response::Drifted`] with one [`SheepDrift`] per app that is
276 /// both registered and different. An app the flock does not have is
277 /// absent from the answer, not reported as unchanged: `Start` will
278 /// register it, so there is nothing to warn about.
279 ConfigDrift {
280 /// The configs to compare against, exactly as [`Self::Start`] would
281 /// carry them. The daemon MUST re-normalize (peer input is
282 /// untrusted, and an unnormalized config would report every default
283 /// it has not spelled out as a difference); failures return
284 /// [`RpcErrorCode::InvalidConfig`].
285 apps: Vec<AppConfig>,
286 },
287 /// Stop matching sheep (stay registered)
288 Stop {
289 /// Which sheep
290 selector: SelectorSpec,
291 },
292 /// Restart matching sheep
293 Restart {
294 /// Which sheep
295 selector: SelectorSpec,
296 },
297 /// Replace each matching sheep with a fresh instance of the same app, one
298 /// instance of an app at a time, so the app has a window in which it can
299 /// stay reachable across the swap
300 Reload {
301 /// Which sheep. No default anywhere in the stack — a reload replaces
302 /// running processes, so the operator names the target, exactly as
303 /// `stop`/`restart`/`delete` do (see `shep reload`).
304 selector: SelectorSpec,
305 },
306 /// Stop + deregister matching sheep
307 Delete {
308 /// Which sheep
309 selector: SelectorSpec,
310 },
311 /// Set how many instances one app runs (see `shep stock`).
312 ///
313 /// # Why a name and not a selector
314 ///
315 /// Every other verb here takes a [`SelectorSpec`], and this one
316 /// deliberately does not. `instances` is a per-app number and instance
317 /// slots are allocated against the same-name group
318 /// (`shep_daemon::assemble::instance_slots`), so a selector matching two
319 /// apps would have to mean either "four of each" or "four in total", and
320 /// neither reading is more obviously right than the other. A name has one
321 /// meaning.
322 ///
323 /// # Why absolute and not a delta
324 ///
325 /// There is no `+N`/`-N` form and there will not be one. An absolute count
326 /// is idempotent — run it twice, get the same flock — where two operators
327 /// sending `+2` against the same app get a number neither of them asked
328 /// for. This project's own trace notes also record a crash on pm2's
329 /// relative-remove path, and those notes exist so shep does not reproduce
330 /// what they record.
331 Scale {
332 /// The app's name, exactly as its config spells it. Not a selector: no
333 /// `all`, no regex, no `fold:`.
334 name: String,
335 /// How many instances the app has when this returns. `0` is refused
336 /// with [`RpcErrorCode::InvalidConfig`] — `normalize` rejects
337 /// `instances == 0` for every other path into the daemon, and `shep
338 /// delete` is the verb for removing an app.
339 count: u32,
340 },
341 /// Attach a short marker to `sheep` for `shep flock` to paint, or clear
342 /// it with `None`.
343 ///
344 /// By NAME rather than a selector, for [`Self::Scale`]'s reason (see its
345 /// own doc above): a smit belongs to a sheep, not to one of its
346 /// instances, and every instance of that name shows it — including one
347 /// spawned after the smit was painted.
348 ///
349 /// Held in memory and scoped to the connection that sent it. When that
350 /// connection closes, for any reason, the smits it painted go with it. A
351 /// publisher therefore republishes rather than publishing on change.
352 ///
353 /// shep does not parse it and has no opinion about what it means.
354 SetSmit {
355 /// Which sheep.
356 sheep: String,
357 /// The marker, or `None` to clear it.
358 smit: Option<Smit>,
359 },
360 /// Reopen every matched sheep's log files, for an external rotator that
361 /// has renamed them (`create`-mode rotation)
362 Reopen {
363 /// Which sheep
364 selector: SelectorSpec,
365 },
366 /// Empty every matched sheep's log files: flush what is still pending,
367 /// then truncate the recorded paths
368 Flush {
369 /// Which sheep. No default anywhere in the stack — this destroys
370 /// log data, so the operator names the target (see `shep flush`).
371 selector: SelectorSpec,
372 },
373 /// Send a named action to every matched sheep over its shepherd channel
374 /// and report what each app says back (see `shep trigger`).
375 Trigger {
376 /// Which sheep. No default anywhere in the stack, matching
377 /// `stop`/`restart`/`reload`/`delete`/`flush`: an operator names the
378 /// target rather than trigger an action against the whole flock by
379 /// accident.
380 selector: SelectorSpec,
381 /// The action name. Free-form — the daemon never declares, parses,
382 /// or validates it; an app that does not recognize the name is
383 /// expected to say so in its own reply rather than stay silent.
384 action: String,
385 /// Argument text for the action, passed through to the app
386 /// verbatim. One opaque string, not structured data: the daemon
387 /// holds no schema for it, matching the shepherd channel's own
388 /// `action` message this ultimately becomes.
389 params: Option<String>,
390 },
391 /// Deliver one signal to every matched sheep's OWN process — never its
392 /// process group (see `shep signal`).
393 Signal {
394 /// Which sheep. No default anywhere in the stack, matching every
395 /// other verb that reaches a running process: an operator names the
396 /// target rather than signal the whole flock by accident.
397 selector: SelectorSpec,
398 /// The signal's name, as
399 /// [`OperatorSignal`](crate::signals::OperatorSignal) spells it — the
400 /// `SIG` prefix and the case are both optional.
401 ///
402 /// A `String` rather than the enum, for the reason
403 /// [`AppConfig::kill_signal`](crate::config::AppConfig::kill_signal)
404 /// is one: the wire stays plain text a person can read in a capture,
405 /// and the daemon re-validates regardless, because peer input is
406 /// untrusted. A name outside the grammar answers
407 /// [`RpcErrorCode::InvalidConfig`].
408 signal: String,
409 },
410 /// Write one line to every matched sheep's stdin (see `shep whisper`).
411 SendLine {
412 /// Which sheep. No default, matching every other verb that reaches a
413 /// running process.
414 selector: SelectorSpec,
415 /// The line, WITHOUT its terminator — the shepherd appends exactly one
416 /// `\n` when it writes. Carrying the terminator here would leave "did
417 /// the caller include one" as a question every hop has to re-answer,
418 /// and a caller that included two would send an empty line the app
419 /// never asked for.
420 ///
421 /// A line containing an embedded newline is refused
422 /// ([`RpcErrorCode::InvalidConfig`]): it would deliver two commands
423 /// where the operator typed one.
424 line: String,
425 },
426 /// Write the muster roll now, bypassing the snapshot writer's debounce
427 SaveRoll,
428 /// Assemble the flock from the muster roll on disk: start every app the
429 /// roll recorded running, leaving every app the flock already has exactly
430 /// as it stands
431 Muster,
432 /// Ask for one dog's `[dog.<name>]` section, as the dog itself parses it
433 DogConfig {
434 /// The dog's name — the config key, not a selector
435 name: String,
436 },
437 /// Start one dog now, marking it as coming from `source`
438 EnableDog {
439 /// The dog's name
440 name: String,
441 /// Where its binary comes from
442 source: DogSource,
443 },
444 /// Stop and deregister one dog
445 ///
446 /// Answers [`Response::Deleted`], the same reply `Delete` gives: disabling
447 /// deregisters exactly as `Delete` does, so this is the same fact and not
448 /// a coincidence of shape. A variant of its own (`DogDisabled`, say) would
449 /// carry nothing `Deleted` does not.
450 DisableDog {
451 /// The dog's name
452 name: String,
453 },
454 /// Ask which dogs this daemon has given up on, and which it is still
455 /// waiting to hear from (`shep daemon reload`, the handover design's
456 /// G13).
457 ///
458 /// Read-only, and about THIS daemon's own handshakes. A dog's recorded
459 /// crate version describes the process that was running when it
460 /// connected, so it says nothing about a dog that has since been
461 /// replaced; the only thing that knows whether a dog can talk to this
462 /// daemon is whether this daemon accepted its handshake. That is what
463 /// this answers, which is why the reading is worth taking AFTER a
464 /// reload rather than before one.
465 ///
466 /// Answers [`Response::DogStaleness`].
467 ///
468 /// # Why this variant does not move `PROTOCOL_VERSION`
469 ///
470 /// The same argument [`Self::HandoverFitness`] makes above, and the
471 /// same gate enforces it: its only caller is `shep daemon reload`, which
472 /// asks it of the successor it has just proven is running this binary's
473 /// own version. An older daemon is never sent it.
474 DogStaleness,
475 /// Ask whether this daemon could hand its flock to a successor in place,
476 /// rather than stopping it and starting it again (`shep daemon reload`).
477 ///
478 /// Read-only, and nothing here triggers a handover. The trigger is a
479 /// signal and always was: a socket request cannot be the trigger, because
480 /// the case that most needs a reload is the one where the daemon refuses
481 /// the client at the handshake. What travels over the socket is the
482 /// DECISION, for a reason a signal cannot serve (spec H3a) -- a signal
483 /// carries no reply, so a daemon that took one, refused, and fell back to
484 /// its own graceful stop would leave the client polling for a successor
485 /// nobody started, with the flock down and staying down.
486 ///
487 /// Answers [`Response::HandoverFitness`]. Every refusal is a feature the
488 /// running daemon cannot yet carry, not an error: the caller falls back
489 /// to a stop-and-start, which is correct behaviour rather than a degraded
490 /// one, and prints the reason to the operator who asked for the reload.
491 ///
492 /// # Why this variant does not move `PROTOCOL_VERSION`
493 ///
494 /// An older daemon cannot deserialize a variant it has never seen, which
495 /// is normally what a bump is for. It is never sent to one. `daemon
496 /// reload` is an exempt verb, so it connects to a mismatched daemon
497 /// deliberately, learns the daemon's crate version from the handshake,
498 /// and takes the stop arm for anything predating the handover without
499 /// ever asking. shep-cli's `commands::daemon` holds that gate and a test
500 /// of its own pins it.
501 HandoverFitness,
502 /// Graceful daemon shutdown
503 KillDaemon,
504 /// Subscribe this connection to bus topics (glob patterns)
505 Subscribe {
506 /// Topic globs, e.g. `process.*`
507 topics: Vec<String>,
508 },
509}
510
511/// Where a dog came from: this binary, or one an operator adopted.
512///
513/// The one thing an operator wants when a dog misbehaves, which is why it
514/// is a column rather than a detail. Carried on [`ProcessInfo::dog`], so a
515/// listing distinguishes the two populations without a second request.
516///
517/// `#[non_exhaustive]`: a future source — a dog fetched from a registry,
518/// say — must not need a protocol version bump (IR-20).
519// wire format: changing existing variants is a breaking change
520#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
521#[serde(tag = "kind", rename_all = "snake_case")]
522#[non_exhaustive]
523pub enum DogSource {
524 /// An argv branch of the shep binary itself (`shep dog <name>`).
525 BuiltIn,
526 /// A binary an operator adopted, run at the daemon's own trust level.
527 Adopted {
528 /// The binary's path, exactly as the operator gave it to `adopt`.
529 path: String,
530 },
531}
532
533/// One process the OS reports as a descendant of a sheep.
534///
535/// # What this is not
536///
537/// It is **not** the set of processes that die with the sheep, and nothing here
538/// should be read as promising that. The list is built by walking the OS's
539/// parent-pid links; the stop ladder acts on the process GROUP, and the two
540/// units diverge in both directions — a lamb that forks and exits leaves its
541/// own children re-parented to init, out of this list and still in the group,
542/// while a `setsid()` grandchild stays in this list and leaves the group.
543/// shep-daemon's `limits` module doc has the full account, and it is the
544/// authority; this is a pointer to it, not a second copy free to drift.
545///
546/// # Why a name and not a command line
547///
548/// `name` is the executable's name as the OS reports it (`node`, `sh`,
549/// `python3`), never its argument vector. A process's argv routinely carries
550/// credentials — a `--password=` flag, a URL with a token in the query string —
551/// and this field rides in `shep describe --format json`, which is output
552/// people paste into bug reports. A pid alone would be safe too, and was
553/// considered; it was rejected because a tree of bare integers sends the
554/// operator to `ps`, which is the work the tree exists to save.
555///
556/// # Why no memory figure
557///
558/// The sheep's own row already reports its whole tree's resident size
559/// ([`ProcessInfo::memory_bytes`]), and a per-lamb breakdown is a profiler's
560/// job. `deferred.md`'s note on this struct's growth asks for exactly this
561/// restraint.
562///
563/// `#[non_exhaustive]`: shep-core is a published library, this type is new, and
564/// the two obvious next fields (a parent pid, so a deep tree can be nested
565/// rather than flattened; a start time) would otherwise be breaking additions
566/// (IR-20). Build one with [`Self::new`].
567// wire format: changing this is a breaking change
568#[non_exhaustive]
569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
570pub struct Lamb {
571 /// The lamb's own pid.
572 pub pid: u32,
573 /// The executable's name, as the OS reports it. Never its command line.
574 pub name: String,
575}
576
577impl Lamb {
578 /// One lamb.
579 ///
580 /// A plain constructor rather than a builder, unlike [`ProcessInfo`]: both
581 /// fields are required and neither is optional or derived, which is the
582 /// case a builder buys nothing for.
583 #[must_use]
584 pub fn new(pid: u32, name: impl Into<String>) -> Self {
585 Self {
586 pid,
587 name: name.into(),
588 }
589 }
590}
591
592/// Why a sheep's process most recently stopped existing under this daemon.
593///
594/// Not shep-daemon's own `ExitOutcome` reused directly: that type lives
595/// behind the spawn-runner seam (`ProcessRunner::wait`, in shep-daemon's
596/// `runner` module) and is free to grow with whatever the real runner needs
597/// to observe next without dragging a breaking wire change behind it — this
598/// one only ever grows on its own say-so. The two happen to carry the same
599/// two fields today because the runner's own observation IS the honest exit
600/// outcome; shep-daemon converts one into the other at the point it records
601/// it (`Actor::handle_exited`), rather than this crate depending on
602/// shep-daemon's internals to reuse its type.
603///
604/// A struct, not two flat `Option<i32>` fields on [`ProcessInfo`] directly:
605/// with two flat fields, "this sheep has never exited under this daemon"
606/// and "it exited, killed by a signal this daemon did not name" are both
607/// all-`None`, and a reader cannot tell those apart. Nested behind
608/// [`ProcessInfo::last_exit`]'s own `Option`, that ambiguity moves up a
609/// level where it belongs: `None` there means "never exited"; `Some` means
610/// "exited, and here is what this daemon knows about it" — which itself
611/// mirrors the OS's own exited-normally/killed-by-signal split
612/// (`WIFEXITED`/`WIFSIGNALED`): ordinarily exactly one of `code`/`signal` is
613/// `Some`. A reader must not assume both can never be `None` together,
614/// though — that would still mean "this daemon recorded an exit; it could
615/// not characterize how" rather than "this sheep never exited", and this
616/// type does not forbid it.
617///
618/// No `#[non_exhaustive]`, unlike every other struct on this wire: those
619/// grow because a discriminator does (`ProcessInfo`'s own doc lists its
620/// four so far); `code`/`signal` is already the complete
621/// exited-normally/killed-by-signal split the runner exposes, this crate
622/// has no libc to derive a richer wait-status decomposition from even if it
623/// wanted one, and there is no forecast next field. Adding the attribute
624/// back later is a compatible change the day a real need appears (IR-16
625/// style); carrying it now on nothing but "might grow" is the exact
626/// speculative case IR-20 warns against.
627// wire format: changing this is a breaking change
628#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
629pub struct ExitInfo {
630 /// The process's own exit code, set on a normal exit (`WIFEXITED`).
631 pub code: Option<i32>,
632 /// The raw unix signal number that ended the process, set when it did
633 /// not exit on its own (`WIFSIGNALED`) — an operator's own `shep stop`
634 /// or `shep delete` included: the process still genuinely stopped by a
635 /// signal, and that stays true information even though shep, not a
636 /// crash, is what asked for it. Raw and platform-specific for the same
637 /// reason [`crate::signals::OperatorSignal`] carries no such accessor —
638 /// see that type's own module doc — so rendering this as a name
639 /// (`SIGKILL` rather than `9`) is a job for whichever OS-aware layer
640 /// reads it, never for this crate.
641 pub signal: Option<i32>,
642}
643
644/// Snapshot of one sheep for listings and events
645// wire format: changing this is a breaking change
646//
647// `out_file`/`err_file` are `Option<String>`, and both halves of that are
648// deliberate:
649//
650// String, not PathBuf. Every path already on this wire travels as a string
651// (`AppConfig::script`, `cwd`, `out_file`, `err_file`, all of which ride in
652// `Request::Start`), so this matches the established representation. It is
653// also the safer failure mode: serde's `PathBuf` impl REFUSES a non-UTF-8
654// path, and that refusal is not local — it aborts the whole `Reply`, so one
655// sheep with an odd log path would blank the entire `ListFlock` for every
656// other sheep. Lossy conversion daemon-side degrades exactly one field of
657// one sheep instead.
658//
659// Option, not a bare String. Semantically the daemon always resolves both
660// paths, so a required field is tempting. But the handshake only compares
661// `PROTOCOL_VERSION` (see shep-daemon's `server.rs`), and adding these
662// fields deliberately does NOT bump it — the evolution rule in this
663// module's parent says additive fields keep the version. A daemon built
664// before this field and a client built after it therefore both announce
665// protocol 1 and connect happily, and that daemon's replies carry no
666// `out_file` key at all. A required `String` would fail to deserialize
667// there, so a new client could not list against an old daemon. `None`
668// means precisely "this peer predates the field" — which readers must
669// render as unknown, NOT as "this sheep has no log file".
670//
671// `cpu_percent`/`memory_bytes` are optional for that same skew reason and
672// for one of their own: a sheep that is not running has no resource use to
673// report, and one that has been up for less than a sampling window has no
674// honest CPU figure. All three cases render as unknown, never as zero.
675//
676// No `Eq`, which every other wire struct in this module derives:
677// `cpu_percent` is an `f32` and floats are only partially ordered. Nothing
678// compares a `ProcessInfo` for total equality — `assert_eq!` needs only
679// `PartialEq`, and no listing is keyed on, hashed by, or sorted by a whole
680// row.
681/// `#[non_exhaustive]`: this struct grows fields over time with no hand-edit
682/// sweep needed across OUT-OF-TREE callers — it forbids a struct literal
683/// outside this crate, not inside it. `sample_info()` and
684/// [`ProcessInfoBuilder`] both still name every field and both still need
685/// updating the day a field is added; what the attribute buys is that
686/// nothing downstream does. `deferred.md`'s own `ProcessInfo` entry defers
687/// SPLITTING it into several smaller types, not growing it — this attribute
688/// plus [`ProcessInfo::builder`] is "deliberately the opposite of forcing
689/// the split early," which is what makes a field like `last_exit` cheap to
690/// add for a concrete operator need, not a reason to withhold one. Use
691/// [`ProcessInfo::builder`] to construct one; the fields stay `pub`, so
692/// reading them and assigning to them are both unchanged.
693#[non_exhaustive]
694#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
695pub struct ProcessInfo {
696 /// Stable numeric id
697 pub id: u32,
698 /// Sheep name
699 pub name: String,
700 /// Lifecycle status
701 pub status: ProcStatus,
702 /// OS pid while running
703 pub pid: Option<u32>,
704 /// Restart count since registration
705 pub restarts: u32,
706 /// Milliseconds since last successful start
707 pub uptime_ms: u64,
708 /// Fold membership
709 pub fold: Option<String>,
710 /// Resolved stdout log path: the app's explicit
711 /// [`AppConfig::out_file`] when it set one, else the daemon-derived
712 /// default. `None` only when the peer daemon predates this field.
713 pub out_file: Option<String>,
714 /// Resolved stderr log path, resolved exactly as [`Self::out_file`]
715 pub err_file: Option<String>,
716 /// Tree CPU as a percentage of one core, over the window since the
717 /// daemon's last periodic sample. `None` when the sheep is not running,
718 /// when it has been up for less than one sampling window, or when the
719 /// peer daemon predates this field — all three of which a reader
720 /// renders as unknown, never as zero.
721 ///
722 /// A value over 100 is a tree using more than one core, not a bug.
723 pub cpu_percent: Option<f32>,
724 /// Tree resident set size in bytes, current as of the reply. `None`
725 /// under the same three conditions as [`Self::cpu_percent`], minus the
726 /// window one — memory needs no baseline.
727 pub memory_bytes: Option<u64>,
728 /// Set when this entry is a dog, naming where the dog came from;
729 /// `None` for a sheep.
730 ///
731 /// Unlike [`Self::cpu_percent`], `None` here does not need to enumerate
732 /// three cases. A daemon built before dogs existed has none, so "not a
733 /// dog" is the true answer whether this peer predates the field or the
734 /// entry is genuinely a sheep — there is no resource-usage-style claim
735 /// a stale zero could get wrong. Do not "fix" this into three cases.
736 pub dog: Option<DogSource>,
737 /// The processes the OS reports as descendants of this sheep, or `None`
738 /// when this reply did not walk for them.
739 ///
740 /// `None` covers two cases and is deliberately not a third: this reply is
741 /// not a `Describe` (only `Describe` walks — the walk costs a second pass
742 /// over the machine's process table, and a flock listing is the thing an
743 /// operator leaves running in a loop), or the peer daemon predates the
744 /// field. `Some(vec![])` is the third case, and the one that means what it
745 /// looks like: walked, and this sheep has no children.
746 ///
747 /// Read [`Lamb`]'s own doc before rendering this. The list is a parent-pid
748 /// walk and is NOT the set of processes a stop kills; any output built from
749 /// it has to say so where the operator will see it.
750 pub lambs: Option<Vec<Lamb>>,
751 /// How this sheep's process most recently stopped existing under this
752 /// daemon. `None` while it has never exited under this daemon — either
753 /// it has not been started yet, or it is still on its very first run —
754 /// and also when the peer daemon predates this field, the same skew
755 /// rule [`Self::out_file`] documents for itself.
756 ///
757 /// Sticky across a respawn, deliberately: this is the daemon's answer
758 /// to "why did it last stop", not "is it stopped right now" — `status`
759 /// and `pid` already answer that, and a sheep back `Online` after a
760 /// crash still has a true story to tell about the crash that restarted
761 /// it. It updates only on the next exit, never cleared by one starting
762 /// back up.
763 pub last_exit: Option<ExitInfo>,
764 /// The marker a dog has asked to have painted beside this sheep, or
765 /// `None` when no dog has painted one — which also covers a peer daemon
766 /// that predates the field, the same skew rule [`Self::out_file`]
767 /// documents for itself.
768 ///
769 /// A `String` rather than a [`Smit`], deliberately: a client decoding a
770 /// listing from a daemon that already validated the text should not have
771 /// to re-run the parser, and [`ProcessInfo`] is a report rather than an
772 /// input. The validation that makes this safe to print happened at the
773 /// daemon's ingress — see [`Smit`] for why there and not at the renderer.
774 ///
775 /// Every instance of a name shows the same marker: smits are keyed by
776 /// sheep name, not by instance id.
777 pub smit: Option<String>,
778 /// Which instance slot of its app this sheep occupies, counting from 0.
779 ///
780 /// `None` when the peer daemon predates the field, the same skew rule
781 /// [`Self::out_file`] documents for itself. Deliberately not a bare
782 /// `u32` defaulted to 0: an app stocked to four instances would then
783 /// report four rows all claiming slot 0, which is the silently-wrong
784 /// zero [`Self::dog`] warns against. A reader that finds `None` should
785 /// render exactly what it rendered before this field existed.
786 pub instance: Option<u32>,
787 /// Whether this dog has completed a handshake with the shepherd that is
788 /// reporting it, and not been refused since; `None` for a sheep.
789 ///
790 /// Read [`Self::dog`]'s own doc first — this field follows it rather
791 /// than [`Self::cpu_percent`], and for the same reason. `None` covers a
792 /// sheep and a peer daemon that predates the field, and collapsing the
793 /// two costs nothing: a sheep never handshakes with anything (it has no
794 /// connection to the shepherd at all, only a supervised process), so
795 /// "no handshake fact to report" is the true answer either way, and a
796 /// reader that finds `None` renders exactly what it rendered before
797 /// this field existed. Do not "fix" this into three cases.
798 ///
799 /// `Some(false)` is the one that matters and it is why this exists.
800 /// [`Self::status`] reports whether a PROCESS is alive, which for a
801 /// sheep is the whole truth and for a dog is not: a dog that cannot
802 /// talk to the shepherd is not doing its job, however alive it is. A
803 /// dog running on a protocol this shepherd refuses is exactly that, and
804 /// before this field a listing reported it `online` with zero restarts
805 /// while its own log filled with refusals.
806 ///
807 /// A fact and not a verdict, deliberately: this says whether the
808 /// handshake happened, never what a renderer should print about it. A
809 /// dog that has only just been spawned has not handshaken yet and is
810 /// perfectly healthy, so the decision about which lifecycle states that
811 /// silence is worth overriding belongs to the reader.
812 pub handshook: Option<bool>,
813 /// Whether the reporting shepherd has GIVEN UP on this dog — restarted
814 /// it once for never answering, watched that not help, and stopped
815 /// restarting it; `None` for a sheep.
816 ///
817 /// The same `None` rule [`Self::handshook`] documents, for the same
818 /// reason: a sheep is never given up on because a sheep never had to
819 /// answer anything, so "no verdict to report" is the true answer both
820 /// for a sheep and for a peer daemon that predates this field, and a
821 /// reader that finds `None` renders exactly what it rendered before the
822 /// field existed. Do not "fix" this into three cases.
823 ///
824 /// **Why this is not derivable from [`Self::handshook`], which is the
825 /// whole reason it exists.** `Some(false)` there covers two dogs whose
826 /// rows are otherwise identical: one spawned three seconds ago that has
827 /// simply not dialled back yet, and one this shepherd has permanently
828 /// stopped restarting. The first needs nothing done about it and the
829 /// second is an incident. Before this field the give-up was a latch
830 /// inside the daemon that no listing could see, so every operator-facing
831 /// surface rendered both as the same word.
832 ///
833 /// A fact and not a verdict, again deliberately. It says the shepherd
834 /// stopped, never why — the why is what the shepherd wrote into that
835 /// dog's own log when it gave up, and it is the one place that can name
836 /// the evidence (`shep bleats <dog>`). A renderer that invented a cause
837 /// here would be re-committing the bug this field was added during: a
838 /// shepherd asserting a cause it never observed.
839 pub dog_stale: Option<bool>,
840}
841
842/// Orders one flock listing the way every operator-facing surface presents
843/// one: by name, then by instance slot, then by id.
844///
845/// # Why name first
846///
847/// An id is assigned at registration, so ordering by it sorts the flock by
848/// an accident of history rather than by anything an operator is looking
849/// for. It is not stable either: a `delete all` followed by a fresh start
850/// moved a real thirteen-app flock from ids 0-10 to 11-21 with nothing
851/// about the apps having changed. A name is what an operator scans a long
852/// listing for, and it survives that churn.
853///
854/// # Why id breaks the tie
855///
856/// A name is unique to an APP, not to a sheep: an app stocked to four
857/// instances puts four rows under one name. Name alone is therefore not a
858/// total order, and an unstable sort would let those four shuffle between
859/// refreshes — visible in `shep flock` and worse in `shep lookout`, which
860/// repolls every two seconds. The id keeps its other job unchanged: it is
861/// still how an operator addresses one instance at `shep stop 11`. It stops
862/// being a sort key and stays an addressing key.
863///
864/// This is the ONLY ordering rule in shep, and the daemon's own
865/// `snapshot_all` calls this function rather than restating it. The order is
866/// `(name, instance, id)`: [`ProcessInfo::instance`] now carries the slot a
867/// row occupies, so a reload that hands slot 0 a fresh id no longer moves
868/// that row out of place. A listing whose rows all carry `None` (an older
869/// peer daemon, or a row with no slot to report) collapses to the same
870/// `(name, id)` order this function used before the field existed, because
871/// `None` sorts before every `Some` and every row in that listing shares it.
872pub fn sort_flock(listing: &mut [ProcessInfo]) {
873 listing.sort_unstable_by(|a, b| {
874 (a.name.as_str(), a.instance, a.id).cmp(&(b.name.as_str(), b.instance, b.id))
875 });
876}
877
878impl ProcessInfo {
879 /// Starts a builder for one sheep's row.
880 ///
881 /// The three required arguments are the three fields no row can omit and
882 /// no reader can default: which sheep this is, what it is called, and
883 /// what state it is in. Everything else is optional, derived, or
884 /// meaningfully absent, which is exactly the shape a builder is for —
885 /// a nine-argument `new` would put `Option<String>, Option<String>,
886 /// Option<f32>, Option<u64>` next to each other at every call site and
887 /// invite a silent transposition the type system could not catch.
888 ///
889 /// No `#[must_use]` here: [`ProcessInfoBuilder`] already carries one,
890 /// which clippy's `double_must_use` lint treats as covering this
891 /// function's return too.
892 pub fn builder(id: u32, name: impl Into<String>, status: ProcStatus) -> ProcessInfoBuilder {
893 ProcessInfoBuilder {
894 info: Self {
895 id,
896 name: name.into(),
897 status,
898 pid: None,
899 restarts: 0,
900 uptime_ms: 0,
901 fold: None,
902 out_file: None,
903 err_file: None,
904 cpu_percent: None,
905 memory_bytes: None,
906 dog: None,
907 lambs: None,
908 last_exit: None,
909 smit: None,
910 instance: None,
911 handshook: None,
912 dog_stale: None,
913 },
914 }
915 }
916}
917
918/// Builds a [`ProcessInfo`], which is `#[non_exhaustive]` and so cannot be
919/// written as a struct literal outside this crate.
920///
921/// Every setter takes the field's own type, `Option` included, rather than
922/// the unwrapped value. That is deliberate and it is the difference between a
923/// straight port and a rewrite: the daemon already holds `Option<u32>` for a
924/// pid and `Option<f32>` for a CPU reading, so `.pid(entry.pid())` carries
925/// across unchanged where `.pid(u32)` would put an `if let` ladder at every
926/// call site. A setter is skipped, not passed `None`, when a row genuinely
927/// has nothing to say about that field.
928///
929/// Defaults for the skipped fields are the ones a not-yet-running sheep has:
930/// no pid, no uptime, no restarts, no resource reading, not a dog, never
931/// exited.
932#[derive(Debug, Clone)]
933#[must_use = "a builder that is never `build`-ed produces no ProcessInfo"]
934pub struct ProcessInfoBuilder {
935 info: ProcessInfo,
936}
937
938impl ProcessInfoBuilder {
939 /// Sets the OS pid; `None` while the sheep is not running.
940 pub fn pid(mut self, pid: Option<u32>) -> Self {
941 self.info.pid = pid;
942 self
943 }
944
945 /// Sets the restart count since registration.
946 pub fn restarts(mut self, restarts: u32) -> Self {
947 self.info.restarts = restarts;
948 self
949 }
950
951 /// Sets milliseconds since the last successful start.
952 pub fn uptime_ms(mut self, uptime_ms: u64) -> Self {
953 self.info.uptime_ms = uptime_ms;
954 self
955 }
956
957 /// Sets fold membership.
958 pub fn fold(mut self, fold: Option<String>) -> Self {
959 self.info.fold = fold;
960 self
961 }
962
963 /// Sets the resolved stdout log path.
964 pub fn out_file(mut self, out_file: Option<String>) -> Self {
965 self.info.out_file = out_file;
966 self
967 }
968
969 /// Sets the resolved stderr log path.
970 pub fn err_file(mut self, err_file: Option<String>) -> Self {
971 self.info.err_file = err_file;
972 self
973 }
974
975 /// Sets tree CPU as a percentage of one core.
976 pub fn cpu_percent(mut self, cpu_percent: Option<f32>) -> Self {
977 self.info.cpu_percent = cpu_percent;
978 self
979 }
980
981 /// Sets tree resident set size in bytes.
982 pub fn memory_bytes(mut self, memory_bytes: Option<u64>) -> Self {
983 self.info.memory_bytes = memory_bytes;
984 self
985 }
986
987 /// Marks this row a dog and names where the dog came from.
988 pub fn dog(mut self, dog: Option<DogSource>) -> Self {
989 self.info.dog = dog;
990 self
991 }
992
993 /// Sets the sheep's lamb list; `None` when this reply did not walk for one.
994 pub fn lambs(mut self, lambs: Option<Vec<Lamb>>) -> Self {
995 self.info.lambs = lambs;
996 self
997 }
998
999 /// Sets how this sheep's process most recently stopped; `None` while it
1000 /// has never exited under this daemon.
1001 pub fn last_exit(mut self, last_exit: Option<ExitInfo>) -> Self {
1002 self.info.last_exit = last_exit;
1003 self
1004 }
1005
1006 /// Sets the marker a dog has painted on this sheep; `None` when none has.
1007 pub fn smit(mut self, smit: Option<String>) -> Self {
1008 self.info.smit = smit;
1009 self
1010 }
1011
1012 /// Sets the instance slot; `None` when the peer daemon predates the field.
1013 pub fn instance(mut self, instance: Option<u32>) -> Self {
1014 self.info.instance = instance;
1015 self
1016 }
1017
1018 /// Sets whether this dog has handshaken with the shepherd; `None` for a
1019 /// sheep, which has no handshake to report.
1020 pub fn handshook(mut self, handshook: Option<bool>) -> Self {
1021 self.info.handshook = handshook;
1022 self
1023 }
1024
1025 /// Sets whether the shepherd has given up restarting this dog; `None`
1026 /// for a sheep, which is never given up on.
1027 pub fn dog_stale(mut self, dog_stale: Option<bool>) -> Self {
1028 self.info.dog_stale = dog_stale;
1029 self
1030 }
1031
1032 /// Finishes the row.
1033 #[must_use]
1034 pub fn build(self) -> ProcessInfo {
1035 self.info
1036 }
1037}
1038
1039/// What happened when the daemon tried to deliver one sheep's triggered
1040/// action.
1041///
1042/// `#[non_exhaustive]`: a future outcome — distinguishing a malformed reply
1043/// from a well-formed one, say, or a second trigger already in flight for
1044/// the same sheep — must not need a protocol version bump (IR-20).
1045// wire format: changing existing variants is a breaking change
1046#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1047#[serde(tag = "kind", rename_all = "snake_case")]
1048#[non_exhaustive]
1049pub enum ActionOutcome {
1050 /// The app answered on the shepherd channel.
1051 Replied {
1052 /// The reply body, exactly as the app sent it.
1053 body: String,
1054 },
1055 /// The sheep had no reachable shepherd channel for the daemon to
1056 /// deliver the action over.
1057 NoChannel,
1058 /// The sheep is a reload drainee — mid-swap, on its way out — and the
1059 /// daemon skipped it rather than deliver the action to a process
1060 /// already being replaced.
1061 Skipped,
1062 /// The daemon delivered the action, but no reply arrived before the
1063 /// app's configured action timeout elapsed.
1064 TimedOut,
1065}
1066
1067/// One matched sheep's row in a `Trigger` reply.
1068///
1069/// `EmptiedFile` (`crates/shep-cli/src/output/rows.rs`) is the precedent for
1070/// a non-`ProcessInfo` row: a reply body has nowhere to live on
1071/// [`ProcessInfo`], and [`Self::outcome`] is per-row rather than a
1072/// whole-request refusal because spec §9's selector grammar (`all`,
1073/// `/regex/`, `fold:`) makes a mixed flock the normal case — the same reason
1074/// `Reopen`/`Flush` report per-item failure inside a success rather than
1075/// failing the whole request.
1076// wire format: changing this is a breaking change
1077#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1078pub struct ActionReply {
1079 /// The sheep's stable id.
1080 pub id: u32,
1081 /// The sheep's name.
1082 pub name: String,
1083 /// What happened when the daemon tried to deliver the action.
1084 pub outcome: ActionOutcome,
1085}
1086
1087/// What happened when the shepherd tried to deliver one signal.
1088///
1089/// `#[non_exhaustive]`: a future outcome — a sheep refused because it is a dog,
1090/// say, or a delivery held while a stop ladder runs — must not need a protocol
1091/// version bump (IR-20).
1092// wire format: changing existing variants is a breaking change
1093#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1094#[serde(tag = "kind", rename_all = "snake_case")]
1095#[non_exhaustive]
1096pub enum SignalOutcome {
1097 /// The kernel accepted the signal for this sheep's pid.
1098 ///
1099 /// Says the signal was delivered, not that the app did anything with it.
1100 /// A signal the app blocks, ignores, or has no handler for is `Delivered`
1101 /// exactly like one it acts on — there is nothing on this path that could
1102 /// tell the difference, and pretending otherwise would be the dishonest
1103 /// half of an honest report.
1104 Delivered,
1105 /// The sheep is registered but has no live process to signal — stopped,
1106 /// errored, or waiting out a restart backoff.
1107 NotRunning,
1108 /// The kernel refused the delivery; carries its reason (`ESRCH` for a
1109 /// process reaped between the lookup and the syscall, `EPERM` for one this
1110 /// daemon may not signal).
1111 Failed {
1112 /// The refusal, as the OS worded it.
1113 reason: String,
1114 },
1115}
1116
1117/// One matched sheep's row in a `Signal` reply.
1118///
1119/// Shaped exactly like [`ActionReply`] and for the same reason: spec §9's
1120/// selector grammar (`all`, `/regex/`, `fold:`) makes a mixed flock the normal
1121/// case, so a per-row outcome beats a whole-request refusal that would leave
1122/// the operator unable to tell which half was taken.
1123// wire format: changing this is a breaking change
1124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1125pub struct SignalReply {
1126 /// The sheep's stable id.
1127 pub id: u32,
1128 /// The sheep's name.
1129 pub name: String,
1130 /// What happened when the shepherd tried to deliver the signal.
1131 pub outcome: SignalOutcome,
1132}
1133
1134/// What happened when the shepherd tried to write one line to a sheep's stdin.
1135///
1136/// `#[non_exhaustive]`: a future outcome — a sheep refused because its pipe is
1137/// backed up, say — must not need a protocol version bump (IR-20).
1138// wire format: changing existing variants is a breaking change
1139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1140#[serde(tag = "kind", rename_all = "snake_case")]
1141#[non_exhaustive]
1142pub enum LineOutcome {
1143 /// The line was written to the pipe and flushed.
1144 ///
1145 /// Says the bytes left the shepherd, not that the app read them. A pipe
1146 /// holds 64 KiB before it blocks, so a short line to an app that never
1147 /// reads its stdin is `Sent` — which is honest, because there is nothing
1148 /// on this path that could tell the difference and a supervisor inventing
1149 /// one would be guessing.
1150 Sent,
1151 /// The sheep has no stdin pipe: its config does not set `stdin = true`, or
1152 /// it is not running.
1153 ///
1154 /// One outcome for two causes, deliberately. The row is read to answer
1155 /// "why did my line not arrive", and both answers are "there is no pipe
1156 /// here"; splitting them would put the operator in front of a distinction
1157 /// with the same fix behind it. A sheep that is not running is visible as
1158 /// such in `shep flock`, which is where that question belongs.
1159 NoStdin,
1160 /// The shepherd had a pipe and did not confirm a write to it; carries
1161 /// why.
1162 ///
1163 /// Three shapes reach it: the write failed (the far end is gone —
1164 /// normally the app exiting between the lookup and the write), the line
1165 /// arrived to find the sheep's queue already full, or the write did not
1166 /// finish inside the shepherd's own bound. The reason names which,
1167 /// because the operator's next move differs.
1168 ///
1169 /// # The last shape does not promise the line was never written
1170 ///
1171 /// "Did not confirm", not "could not write", and the difference is the
1172 /// operator's whole decision about retrying. A write that timed out is a
1173 /// write the shepherd stopped WAITING for: the bytes may be part-written
1174 /// into a pipe the app is not draining, and they land in full the moment
1175 /// it does. There is no way to take them back — abandoning a write
1176 /// halfway would leave a partial line in the pipe, which is worse than a
1177 /// slow one.
1178 ///
1179 /// What the shepherd does do is drop a line still QUEUED behind that one
1180 /// once its caller has given up, so retrying a `sendline` cannot pile
1181 /// duplicates up behind a wedged pipe and deliver them together later.
1182 /// The first line of a retry sequence is the one that can still arrive
1183 /// late; treat a retry as a second command, not a repeat of the first.
1184 NotWritten {
1185 /// What went wrong, in plain English.
1186 reason: String,
1187 },
1188}
1189
1190/// One matched sheep's row in a `SendLine` reply.
1191///
1192/// Same shape and same argument as [`ActionReply`] and [`SignalReply`]: spec
1193/// §9's selector grammar makes a mixed flock the normal case, so an outcome
1194/// per row beats a whole-request refusal.
1195// wire format: changing this is a breaking change
1196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1197pub struct LineReply {
1198 /// The sheep's stable id.
1199 pub id: u32,
1200 /// The sheep's name.
1201 pub name: String,
1202 /// What happened.
1203 pub outcome: LineOutcome,
1204}
1205
1206/// A dog's `[dog.<name>]` config section, carried as TOML text.
1207///
1208/// This travels over the socket rather than the child's environment for
1209/// exactly one reason: a dog's section routinely holds webhook credentials
1210/// (a Discord or Slack URL with a bearer token embedded), and the socket
1211/// path keeps that out of the process table and out of crash dumps. A
1212/// derived `Debug` on [`Response`] would undo that the moment something
1213/// logs a reply — see the manual `Debug` below, which prints only a length.
1214///
1215/// `#[serde(transparent)]` makes the wire representation identical to a
1216/// bare `String`: this newtype changes nothing about
1217/// [`crate::protocol::PROTOCOL_VERSION`] or the pinned snapshot fixtures.
1218#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1219#[serde(transparent)]
1220pub struct DogSectionToml(String);
1221
1222impl DogSectionToml {
1223 /// The TOML text, empty when the file has no such section.
1224 #[must_use]
1225 pub fn as_str(&self) -> &str {
1226 &self.0
1227 }
1228}
1229
1230impl From<String> for DogSectionToml {
1231 fn from(toml: String) -> Self {
1232 Self(toml)
1233 }
1234}
1235
1236impl core::ops::Deref for DogSectionToml {
1237 type Target = str;
1238
1239 fn deref(&self) -> &str {
1240 &self.0
1241 }
1242}
1243
1244/// Debug does not print the section body (IR-41) — see the type doc for why.
1245/// Exact-string-tested below (`dog_section_toml_debug_does_not_leak`) so a
1246/// future `#[derive(Debug)]` fails that test instead of silently reopening
1247/// the leak.
1248impl fmt::Debug for DogSectionToml {
1249 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250 write!(f, "DogSectionToml(<{} bytes>)", self.0.len())
1251 }
1252}
1253
1254/// One registered sheep whose stored config differs from a caller's copy:
1255/// the answer [`Request::ConfigDrift`] is asking for
1256///
1257/// Field NAMES only, never their values. This is built to be printed at an
1258/// operator, and [`AppConfig::env`](crate::config::AppConfig::env) carries
1259/// secrets, so a differing `env` reports `"env"` and nothing more (IR-41).
1260/// `Debug` is derived for that reason: there is nothing here to redact.
1261// wire format: changing field names is a breaking change
1262//
1263// `#[non_exhaustive]`: shep-core is a published library, an out-of-tree
1264// consumer can match or construct this exhaustively today, and a third field
1265// (which side is newer, say) would break them with no version bump to say
1266// so (IR-20). [`SheepDrift::new`] is how the daemon builds one.
1267#[non_exhaustive]
1268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1269pub struct SheepDrift {
1270 /// The sheep's name. Both configs share it by construction: it is what
1271 /// matched them to each other.
1272 pub name: String,
1273 /// The [`AppConfig`] fields that differ, in
1274 /// field-name order. Never empty: a sheep with nothing to report is left
1275 /// out of the answer entirely.
1276 pub fields: Vec<String>,
1277}
1278
1279impl SheepDrift {
1280 /// Builds one sheep's report.
1281 ///
1282 /// No builder, unlike [`ProcessInfo`]: both fields are required and
1283 /// neither can be defaulted, so there is no optional surface for one to
1284 /// spare a caller.
1285 #[must_use]
1286 pub fn new(name: impl Into<String>, fields: Vec<String>) -> Self {
1287 Self {
1288 name: name.into(),
1289 fields,
1290 }
1291 }
1292}
1293
1294/// One RPC response (pairs with [`Request`] variants)
1295///
1296/// Ten variants carry a bare `Vec<ProcessInfo>` (`Flock`, `Described`,
1297/// `Started`, `Stopped`, `Restarted`, `Reloading`, `Scaled`, `Reopened`,
1298/// `Flushed`, `Mustered`), and that repetition is intentional — do not
1299/// collapse them into one. Each names which request it answers, which is what
1300/// lets a variant diverge later without a protocol bump: `Reloading` already
1301/// means an acceptance rather than a result, `Scaled` already means only the
1302/// survivors on a scale-down rather than every matched row, and `Mustered`
1303/// already means "every sheep of every restored app" rather than "what this
1304/// call started". A single `Listing(Vec<ProcessInfo>)` would have to
1305/// relitigate all three as a breaking change.
1306// wire format: changing existing variants is a breaking change
1307//
1308// `large_enum_variant` allowed, not fixed: `DogStarted` holds a whole
1309// `ProcessInfo` inline where every other variant holds a `Vec` of them, and
1310// adding `smit` to that struct is what pushed the spread past the lint's
1311// threshold. Clippy's remedy is to box the payload, which would be a source
1312// break for every `Response::DogStarted(info)` in and out of this workspace
1313// — for nothing: a `Response` is built once per reply and serialized
1314// immediately, so the size it occupies on one stack frame in between is not
1315// a cost anybody pays. The wire shape is identical either way.
1316#[allow(clippy::large_enum_variant)]
1317#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1318#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
1319#[non_exhaustive]
1320pub enum Response {
1321 /// Answer to `Ping`
1322 Pong,
1323 /// Answer to `ListFlock`
1324 Flock(Vec<ProcessInfo>),
1325 /// Answer to `Describe`
1326 Described(Vec<ProcessInfo>),
1327 /// Answer to `Start`
1328 Started(Vec<ProcessInfo>),
1329 /// Answer to `ConfigDrift`: one entry per app that is registered under a
1330 /// config different from the one asked about, and no entry for anything
1331 /// else. An empty vector means every app asked about either matches or
1332 /// is not registered at all.
1333 Drifted(Vec<SheepDrift>),
1334 /// Answer to `Stop`
1335 Stopped(Vec<ProcessInfo>),
1336 /// Answer to `Restart`
1337 Restarted(Vec<ProcessInfo>),
1338 /// Answer to `Reload` — an ACCEPTANCE, not a result, and the only reply
1339 /// in this enum carrying a flock listing that names one rather than
1340 /// finished work. [`Self::ShuttingDown`] is an acceptance too, sent
1341 /// before the daemon actually goes down, but it carries nothing.
1342 ///
1343 /// One instance costs a readiness wait plus a drain in the worst case, so
1344 /// a clustered app outlasts any deadline a client is allowed to ask for.
1345 /// The daemon therefore answers as soon as the reload is accepted, with
1346 /// the matched sheep as they stood at that moment, and the swaps report
1347 /// themselves on the bus — `process.reload`, `process.reloaded`,
1348 /// `process.reload_abandoned`. A matched sheep with nothing to replace is
1349 /// listed here as the no-op success it is, so this carries the same
1350 /// matches `Describe` would.
1351 Reloading(Vec<ProcessInfo>),
1352 // The order is cited as [`sort_flock`]'s shared rule rather than restated
1353 // as this reply's own, so the two cannot drift apart.
1354 /// Answer to `Scale` — the app's instances that will REMAIN, one row
1355 /// each, by name, then by instance slot, then by id ([`sort_flock`]).
1356 /// Every row shares one name here, so in practice that is slot order,
1357 /// with the id breaking a tie only where two rows report the same slot.
1358 ///
1359 /// Scaling up, these are the instances that exist, the new ones included,
1360 /// and the answer is complete.
1361 ///
1362 /// Scaling down, these are the survivors and the departing instances are
1363 /// deliberately absent, even though they are still running their kill
1364 /// ladders as this reply is written. The operator asked for a number; this
1365 /// is that number of rows. Listing the departing ones as well would answer
1366 /// a `scale web 2` with four rows, which is the one thing the reply must
1367 /// not do. The departures report themselves on the bus as `process.delete`
1368 /// — the same split `Reloading` already makes between an acceptance and
1369 /// the swaps that follow it.
1370 Scaled(Vec<ProcessInfo>),
1371 /// Answer to `SetSmit` — every instance of the named sheep, one row
1372 /// each, each carrying the smit as it now stands.
1373 ///
1374 /// Its own variant rather than one of the ten above, on this enum's own
1375 /// stated terms: each of them names which request it answers so that one
1376 /// can diverge later without a protocol bump. A future `SetSmit` reply
1377 /// that also reported which connection holds the mark would have nowhere
1378 /// to go if this shared `Scaled`.
1379 SmitPainted(Vec<ProcessInfo>),
1380 /// Answer to `Delete` — ids removed
1381 Deleted(Vec<u32>),
1382 /// Answer to `Reopen` — every matched sheep, running or not. A sheep with
1383 /// no live log pump has nothing to reopen and is reported as a success,
1384 /// so this carries the same matches `Describe` would.
1385 Reopened(Vec<ProcessInfo>),
1386 /// Answer to `Flush` — one row per matched sheep, running or not, exactly
1387 /// as [`Self::Reopened`].
1388 ///
1389 /// One row per SHEEP, not per file emptied. Several sheep can share one
1390 /// log path (`merge_logs`, or an explicit `out_file` on a multi-instance
1391 /// app), and the daemon truncates each distinct path once — but the
1392 /// selector names sheep, so the answer names sheep, and the count here
1393 /// matches what `Describe` would return for the same selector.
1394 Flushed(Vec<ProcessInfo>),
1395 /// Answer to `Trigger` — one [`ActionReply`] row per matched sheep,
1396 /// carrying what each one answered rather than a flock listing:
1397 /// `ProcessInfo` has nowhere to hold a reply body.
1398 Triggered(Vec<ActionReply>),
1399 /// Answer to `Signal` — one [`SignalReply`] row per matched sheep.
1400 ///
1401 /// Not a flock listing: what a caller wants back is per-instance delivery,
1402 /// and [`ProcessInfo`] has nowhere to hold it. Same reasoning, and the
1403 /// same row-shaped answer, as [`Self::Triggered`].
1404 Signalled(Vec<SignalReply>),
1405 /// Answer to `SendLine` — one [`LineReply`] row per matched sheep.
1406 SentLine(Vec<LineReply>),
1407 /// Answer to `SaveRoll`
1408 RollSaved {
1409 /// Absolute path of the roll the daemon wrote
1410 path: String,
1411 /// How many apps that roll records
1412 apps: u32,
1413 },
1414 /// Answer to `Muster` — every sheep of every app the roll restored, not
1415 /// only the ones this call spawned.
1416 ///
1417 /// The distinction is the whole point of the reply. Assembling a flock
1418 /// that is already assembled starts nothing, so a listing of what this
1419 /// call spawned would be empty there — indistinguishable from an empty
1420 /// roll, which is the one outcome an operator needs to tell apart.
1421 Mustered(Vec<ProcessInfo>),
1422 /// Answer to `DogConfig` — the dog's own section, rendered back to TOML.
1423 ///
1424 /// `toml` is [`DogSectionToml`], not a bare `String`: this text
1425 /// routinely carries webhook credentials, and the newtype's manual
1426 /// `Debug` keeps them out of a `{:?}`-formatted `Response` — see that
1427 /// type's docs for why the section travels over the socket at all.
1428 DogSection {
1429 /// The `[dog.<name>]` table as TOML text, empty when the file has
1430 /// no such section
1431 toml: DogSectionToml,
1432 },
1433 /// Answer to `EnableDog` — the dog as it stands now
1434 DogStarted(ProcessInfo),
1435 /// Answer to `DogStaleness` — this daemon's own handshake record, split
1436 /// into the dogs it has given up on and the dogs it is still waiting on.
1437 ///
1438 /// Two lists rather than one because they are answers to two different
1439 /// questions, and only one of them is reportable. `stale` is a
1440 /// finding: those dogs were refused, restarted from the binary on disk,
1441 /// and refused again. `pending` is a reason to ask again: those
1442 /// dogs have not finished settling, so a reading taken now would be a
1443 /// guess about them rather than a fact.
1444 ///
1445 /// Names only. What a stale dog's crate version is does not answer the
1446 /// question a caller is asking — two builds differing only in the
1447 /// protocol they speak report the same version — so carrying one here
1448 /// would invite exactly the inference it cannot support.
1449 DogStaleness {
1450 /// Dogs this daemon has refused twice: once on the handshake that
1451 /// bought them a restart from disk, and again after it. It will not
1452 /// restart them a third time (the handover design's G8).
1453 stale: Vec<String>,
1454 /// Dogs this daemon is still waiting to hear a final answer from —
1455 /// one whose restart is in flight, or one it supervises that has
1456 /// not handshook yet. Neither stale nor known healthy.
1457 pending: Vec<String>,
1458 },
1459 /// Answer to `HandoverFitness`: `None` when the whole flock can be
1460 /// carried across a daemon handover, and otherwise the sentence saying
1461 /// which sheep cannot be and why.
1462 ///
1463 /// A rendered sentence rather than a structured reason, deliberately. The
1464 /// set of things a handover cannot yet carry is exactly the set of things
1465 /// that phase has not built, so it changes with every phase that widens
1466 /// it, and a wire enum would make each of those a protocol change for a
1467 /// string the client does nothing with but print. The daemon owns the
1468 /// wording because the daemon owns the gate.
1469 HandoverFitness {
1470 /// Why the flock cannot be handed over in place, or `None` when it
1471 /// can.
1472 refusal: Option<String>,
1473 },
1474 /// Answer to `Subscribe`
1475 Subscribed,
1476 /// Answer to `KillDaemon`
1477 ShuttingDown,
1478}
1479
1480/// A request frame
1481// wire format: changing this is a breaking change
1482#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1483pub struct Envelope {
1484 /// Per-connection request id
1485 pub id: u64,
1486 /// Client-imposed deadline (daemon aborts work past it)
1487 pub deadline_ms: Option<u64>,
1488 /// The request
1489 pub body: Request,
1490}
1491
1492/// A reply frame
1493///
1494/// `result` uses serde's stock `Result` representation — the wire carries
1495/// `{"Ok": ...}` / `{"Err": ...}` (capitalized keys). Deliberate, pinned by
1496/// snapshot: stock serde beats a custom enum the client would convert anyway.
1497// wire format: changing this is a breaking change
1498#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1499pub struct Reply {
1500 /// Echoes [`Envelope::id`]
1501 pub id: u64,
1502 /// The outcome
1503 pub result: Result<Response, RpcError>,
1504}
1505
1506/// Handshake outcome: `HelloAck` or a typed refusal (spec §6 —
1507/// version skew is an error, not silence). Same `Ok`/`Err` wire shape
1508/// as [`Reply::result`]; refusals use [`RpcErrorCode::ProtocolMismatch`].
1509pub type HelloReply = Result<HelloAck, RpcError>;
1510
1511/// Structured RPC failure
1512// wire format: changing this is a breaking change
1513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1514pub struct RpcError {
1515 /// Machine-readable code
1516 pub code: RpcErrorCode,
1517 /// Human-readable message (plain English, no theme)
1518 pub message: String,
1519 /// The daemon's own crate version, when it chose to name it.
1520 ///
1521 /// Set on a [`RpcErrorCode::ProtocolMismatch`] refusal, where it is the
1522 /// only place a client can learn it: the refusal reports the daemon's
1523 /// PROTOCOL, and [`HelloAck::daemon_version`] never arrives. `shep
1524 /// daemon reload` picks its mechanism by version, and a protocol bump is
1525 /// exactly when that choice matters.
1526 ///
1527 /// `None` on every other error, and on any refusal from a daemon built
1528 /// before this field existed — which no upgrade can change, so a reader
1529 /// must treat `None` as "unknown" and take the conservative path.
1530 ///
1531 /// Additive by construction: absent on the wire rather than `null`, and
1532 /// ignored by a client too old to know it, so
1533 /// [`crate::protocol::PROTOCOL_VERSION`] does not move for it.
1534 #[serde(default, skip_serializing_if = "Option::is_none")]
1535 pub daemon_version: Option<String>,
1536}
1537
1538/// Machine-readable RPC error codes
1539// wire format: changing existing variants is a breaking change
1540#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1541#[serde(rename_all = "snake_case")]
1542#[non_exhaustive]
1543pub enum RpcErrorCode {
1544 /// Selector matched nothing
1545 NotFound,
1546 /// Config failed validation daemon-side
1547 InvalidConfig,
1548 /// Spawn failed (exec error, permissions)
1549 SpawnFailed,
1550 /// Handshake protocol version mismatch
1551 ProtocolMismatch,
1552 /// Unexpected daemon-side failure
1553 Internal,
1554 /// The request's deadline expired before the daemon finished it
1555 DeadlineExceeded,
1556}
1557
1558impl RpcErrorCode {
1559 /// Every variant, for code that needs to iterate them all.
1560 ///
1561 /// `#[non_exhaustive]` forces a `_` arm on any match written outside
1562 /// this crate, which would silently swallow a variant added here and
1563 /// never updated there (shep-cli's exit-code mapping test is the
1564 /// motivating case — see `crates/shep-cli/src/exit.rs`). Downstream
1565 /// crates should iterate `ALL` instead of hand-writing their own list
1566 /// that the compiler can't check.
1567 ///
1568 /// Kept honest by a private `assert_all_lists_every_variant` fn right
1569 /// below: read that doc for how a forgotten variant is caught here,
1570 /// where `#[non_exhaustive]` has no effect.
1571 pub const ALL: [Self; 6] = [
1572 Self::NotFound,
1573 Self::InvalidConfig,
1574 Self::SpawnFailed,
1575 Self::ProtocolMismatch,
1576 Self::Internal,
1577 Self::DeadlineExceeded,
1578 ];
1579
1580 /// Never called; exists purely so this crate fails to build if a
1581 /// variant is added to [`RpcErrorCode`] without also adding it to
1582 /// [`Self::ALL`].
1583 ///
1584 /// `#[non_exhaustive]` only forces a wildcard arm on matches written
1585 /// *outside* this crate — inside the crate that defines the enum, a
1586 /// match with no `_` arm is still checked for exhaustiveness (E0004),
1587 /// so a new variant breaks this build until it gets an arm here. Each
1588 /// arm indexes a fixed literal position into [`Self::ALL`], so growing
1589 /// the enum without growing the array is caught too: rustc denies an
1590 /// out-of-bounds constant array index by default.
1591 #[allow(dead_code)]
1592 const fn assert_all_lists_every_variant(code: Self) -> Self {
1593 match code {
1594 Self::NotFound => Self::ALL[0],
1595 Self::InvalidConfig => Self::ALL[1],
1596 Self::SpawnFailed => Self::ALL[2],
1597 Self::ProtocolMismatch => Self::ALL[3],
1598 Self::Internal => Self::ALL[4],
1599 Self::DeadlineExceeded => Self::ALL[5],
1600 }
1601 }
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606 use super::*;
1607 use crate::config::AppConfig;
1608 use crate::protocol::PROTOCOL_VERSION;
1609 use crate::status::ProcStatus;
1610
1611 fn sample_info() -> ProcessInfo {
1612 ProcessInfo {
1613 id: 3,
1614 name: "web".to_string(),
1615 status: ProcStatus::Online,
1616 pid: Some(4242),
1617 restarts: 1,
1618 uptime_ms: 60_000,
1619 fold: Some("backend".to_string()),
1620 out_file: Some("/home/ada/.shep/logs/web-0-out.log".to_string()),
1621 err_file: Some("/home/ada/.shep/logs/web-0-err.log".to_string()),
1622 // 12.5 rather than a rounder-looking 12.3: an insta JSON
1623 // snapshot is only stable across platforms for a float the
1624 // binary representation holds exactly.
1625 cpu_percent: Some(12.5),
1626 memory_bytes: Some(48 * 1024 * 1024),
1627 dog: None,
1628 lambs: None,
1629 // `restarts: 1` above already says this sheep crashed once and
1630 // came back; a code rather than `None` is the honest exit that
1631 // caused it, not a fact this fixture invents.
1632 last_exit: Some(ExitInfo {
1633 code: Some(1),
1634 signal: None,
1635 }),
1636 smit: None,
1637 instance: None,
1638 handshook: None,
1639 dog_stale: None,
1640 }
1641 }
1642
1643 /// fails if the builder's defaults drift from what a registered-but-not-yet
1644 /// running sheep actually looks like. A builder that quietly defaulted
1645 /// `uptime_ms` to something non-zero, or `restarts` to 1, would put a wrong
1646 /// number in front of an operator with nothing to compare it against.
1647 #[test]
1648 fn a_builder_with_nothing_set_is_a_sheep_that_has_not_run() {
1649 let info = ProcessInfo::builder(3, "web", ProcStatus::Stopped).build();
1650
1651 assert_eq!(info.id, 3);
1652 assert_eq!(info.name, "web");
1653 assert_eq!(info.status, ProcStatus::Stopped);
1654 assert_eq!(info.pid, None);
1655 assert_eq!(info.restarts, 0);
1656 assert_eq!(info.uptime_ms, 0);
1657 assert_eq!(info.fold, None);
1658 assert_eq!(info.out_file, None);
1659 assert_eq!(info.err_file, None);
1660 assert_eq!(info.cpu_percent, None);
1661 assert_eq!(info.memory_bytes, None);
1662 assert_eq!(info.dog, None);
1663 assert_eq!(info.lambs, None);
1664 assert_eq!(info.last_exit, None);
1665 }
1666
1667 /// fails if any setter writes a field other than its own — the failure a
1668 /// twelve-field builder is most likely to ship, and one no individual
1669 /// round-trip test would catch. Every field is given a value distinct from
1670 /// every other field's default, so a copy-pasted setter body shows up as a
1671 /// mismatch rather than as a coincidence.
1672 #[test]
1673 fn every_setter_writes_its_own_field_and_no_other() {
1674 let built = ProcessInfo::builder(3, "web", ProcStatus::Online)
1675 .pid(Some(4242))
1676 .restarts(1)
1677 .uptime_ms(60_000)
1678 .fold(Some("backend".to_string()))
1679 .out_file(Some("/home/ada/.shep/logs/web-0-out.log".to_string()))
1680 .err_file(Some("/home/ada/.shep/logs/web-0-err.log".to_string()))
1681 .cpu_percent(Some(12.5))
1682 .memory_bytes(Some(48 * 1024 * 1024))
1683 .dog(None)
1684 .last_exit(Some(ExitInfo {
1685 code: Some(1),
1686 signal: None,
1687 }))
1688 .build();
1689
1690 // `sample_info()` is still a struct literal, on purpose: it is the one
1691 // place in the workspace that names every field by hand, so this
1692 // comparison fails the day the struct grows a field the builder cannot
1693 // set. That is the point of comparing against it rather than against
1694 // another builder call.
1695 assert_eq!(built, sample_info());
1696
1697 // `dog` is the one field the comparison above cannot speak for, and it
1698 // is the field the whole dogs subsystem reads. `sample_info()`'s `dog`
1699 // is `None`, which is also the builder's default, so a `dog` setter with
1700 // an EMPTY BODY passes the assert_eq! above and passes it for the wrong
1701 // reason. `sample_info()` cannot be changed to `Some(..)` to fix that —
1702 // it feeds `reply_wire_snapshots` and `bus_event_wire_snapshots`, so
1703 // altering it moves pinned bytes. So the field gets its own line, with a
1704 // value nothing defaults to.
1705 assert_eq!(
1706 ProcessInfo::builder(1, "metrics", ProcStatus::Online)
1707 .dog(Some(DogSource::BuiltIn))
1708 .build()
1709 .dog,
1710 Some(DogSource::BuiltIn),
1711 "an empty `dog` setter body is invisible to the comparison above"
1712 );
1713
1714 // `lambs` is the second field the comparison above cannot speak for,
1715 // for the identical reason `dog` is the first: `sample_info()`'s value
1716 // is `None`, which is also the builder's default, so an EMPTY `lambs`
1717 // setter body passes the `assert_eq!` above. And `sample_info()` still
1718 // cannot be changed to a `Some(..)` — it feeds `reply_wire_snapshots`
1719 // and `bus_event_wire_snapshots`, so altering it moves pinned bytes.
1720 assert_eq!(
1721 ProcessInfo::builder(1, "web", ProcStatus::Online)
1722 .lambs(Some(vec![Lamb::new(4243, "node")]))
1723 .build()
1724 .lambs,
1725 Some(vec![Lamb::new(4243, "node")]),
1726 "an empty `lambs` setter body is invisible to the comparison above"
1727 );
1728
1729 // `smit` is the third, on the same terms, and it is the field a
1730 // third party writes — so an empty setter body here would silently
1731 // drop every dog's mark rather than merely lose a decoration.
1732 assert_eq!(
1733 ProcessInfo::builder(1, "web", ProcStatus::Online)
1734 .smit(Some("\u{25b2} main@a1b2c3".to_string()))
1735 .build()
1736 .smit
1737 .as_deref(),
1738 Some("\u{25b2} main@a1b2c3"),
1739 "an empty `smit` setter body is invisible to the comparison above"
1740 );
1741
1742 // `handshook` is the fourth field, on the same terms as the three
1743 // above: `sample_info()`'s value is `None`, which is also the
1744 // builder's default, so an EMPTY `handshook` setter body would pass
1745 // the `assert_eq!` above. `sample_info()` still cannot be changed to
1746 // a `Some(..)` — it feeds `reply_wire_snapshots` and
1747 // `bus_event_wire_snapshots`, so altering it moves pinned bytes.
1748 assert_eq!(
1749 ProcessInfo::builder(1, "web", ProcStatus::Online)
1750 .handshook(Some(false))
1751 .build()
1752 .handshook,
1753 Some(false),
1754 "an empty `handshook` setter body is invisible to the comparison above"
1755 );
1756
1757 // `dog_stale` is the fifth, and the pairing is the point: it and
1758 // `handshook` are both `None` by default, so a setter that dropped
1759 // this one would leave every dog row saying "silent" and never
1760 // "given up on" -- the exact distinction the field was added to
1761 // carry.
1762 assert_eq!(
1763 ProcessInfo::builder(1, "web", ProcStatus::Online)
1764 .dog_stale(Some(true))
1765 .build()
1766 .dog_stale,
1767 Some(true),
1768 "an empty `dog_stale` setter body is invisible to the comparison above"
1769 );
1770 }
1771
1772 /// fails if `lambs` collapses to a bare `Vec`. The three states are the point:
1773 /// a peer that predates the field and a reply that did not walk the tree are
1774 /// both `None`, and a sheep that really has no children is `Some(vec![])`. A
1775 /// `Vec` would render the first two as "this sheep has no lambs", which is a
1776 /// claim neither of them makes.
1777 #[test]
1778 fn lambs_distinguishes_not_walked_from_walked_and_empty() {
1779 let not_walked = ProcessInfo::builder(1, "web", ProcStatus::Online).build();
1780 assert_eq!(not_walked.lambs, None);
1781
1782 let walked_empty = ProcessInfo::builder(1, "web", ProcStatus::Online)
1783 .lambs(Some(Vec::new()))
1784 .build();
1785 assert_eq!(walked_empty.lambs, Some(Vec::new()));
1786 }
1787
1788 /// fails if a `ProcessInfo` from a daemon that predates the field stops
1789 /// deserializing. That is the whole reason the field is optional and the reason
1790 /// `PROTOCOL_VERSION` does not move for it — an old daemon's reply carries no
1791 /// `lambs` key at all, and a required field there would mean a new client could
1792 /// not list against an old daemon.
1793 #[test]
1794 fn a_process_info_without_a_lambs_key_still_deserializes() {
1795 let fixture = r#"{
1796 "id": 3, "name": "web", "status": "online", "pid": 4242,
1797 "restarts": 0, "uptime_ms": 100, "fold": null,
1798 "out_file": null, "err_file": null,
1799 "cpu_percent": null, "memory_bytes": null, "dog": null
1800 }"#;
1801 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
1802 assert_eq!(info.lambs, None);
1803 }
1804
1805 /// fails if a lamb stops carrying its name, or starts carrying a command line.
1806 /// The name is `sysinfo`'s executable name, never argv — argv routinely holds
1807 /// credentials (`--password=`, `?token=`) and `shep describe --format json` is
1808 /// output people paste into issues.
1809 #[test]
1810 fn a_lamb_is_a_pid_and_an_executable_name() {
1811 let lamb = Lamb::new(4243, "node");
1812 let json = serde_json::to_string(&lamb).unwrap();
1813 assert_eq!(json, r#"{"pid":4243,"name":"node"}"#);
1814 assert_eq!(serde_json::from_str::<Lamb>(&json).unwrap(), lamb);
1815 }
1816
1817 /// fails if `DogSource` loses its `tag = "kind"` or its snake_case
1818 /// rename, and fails if `Adopted`'s `path` is renamed — any of the three
1819 /// changes one of these two strings while every type-level test in this
1820 /// module keeps passing. The marker is what the CLI splits two tables on
1821 /// and what the metrics dog reports a health gauge from, so a silent
1822 /// rename here is a silently empty dogs table.
1823 #[test]
1824 fn a_dog_source_serializes_snake_case_under_its_kind() {
1825 assert_eq!(
1826 serde_json::to_string(&DogSource::BuiltIn).unwrap(),
1827 r#"{"kind":"built_in"}"#
1828 );
1829 let adopted = DogSource::Adopted {
1830 path: "/usr/local/bin/shep-otel".to_string(),
1831 };
1832 let wire = r#"{"kind":"adopted","path":"/usr/local/bin/shep-otel"}"#;
1833 assert_eq!(serde_json::to_string(&adopted).unwrap(), wire);
1834 assert_eq!(serde_json::from_str::<DogSource>(wire).unwrap(), adopted);
1835 }
1836
1837 /// fails if `dog` stops being optional. A daemon built before dogs
1838 /// sends a reply with no such key and still announces protocol 1, so a
1839 /// required field would make a current client unable to list against it
1840 /// at all — the same skew rule `out_file` and `cpu_percent` are pinned
1841 /// under, and the same committed-byte-fixture proof.
1842 #[test]
1843 fn v1_process_info_without_a_dog_marker_still_deserializes() {
1844 let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend","out_file":"/l/o.log","err_file":"/l/e.log","cpu_percent":12.5,"memory_bytes":50331648}"#;
1845 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
1846 assert_eq!(info.dog, None);
1847 }
1848
1849 /// fails if `last_exit` stops being optional. A daemon built before this
1850 /// field sends a reply with no such key and still announces protocol 1 —
1851 /// the same skew rule every other field added after `Hello`/`HelloAck`
1852 /// were fixed is pinned under.
1853 ///
1854 /// This is also the empirical proof of a subtle point: none of
1855 /// `ProcessInfo`'s fields carry `#[serde(default)]`, and there is
1856 /// no container-level one either, yet the doc comments on `out_file` and
1857 /// `cpu_percent` both claim "`None` only when the peer daemon predates
1858 /// this field" as though one existed. Serde's `Deserialize` derive
1859 /// special-cases a field whose type is syntactically `Option<...>`: a
1860 /// missing key resolves to `None` without `#[serde(default)]` doing
1861 /// anything, because the derive macro recognizes the `Option` wrapper
1862 /// itself and generates that fallback for it. Those doc comments were
1863 /// right; they just named the wrong mechanism, or none. This test pins
1864 /// the real one for `last_exit` specifically — with `dog` and `lambs`
1865 /// present but `last_exit` genuinely absent from the JSON below — rather
1866 /// than leaving it as an inference from `v1_process_info_without_a_dog_
1867 /// marker_still_deserializes` above.
1868 #[test]
1869 fn a_process_info_without_a_last_exit_key_still_deserializes() {
1870 let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend","out_file":"/l/o.log","err_file":"/l/e.log","cpu_percent":12.5,"memory_bytes":50331648,"dog":null,"lambs":null}"#;
1871 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
1872 assert_eq!(info.last_exit, None);
1873 }
1874
1875 /// fails if a `Signal` frame stops carrying the signal name as plain text, or
1876 /// if the outcome rows stop distinguishing their three cases. The name travels
1877 /// as a `String` on purpose (`AppConfig::kill_signal` does the same): the wire
1878 /// stays readable and the daemon re-validates, which it has to do anyway
1879 /// because peer input is untrusted.
1880 #[test]
1881 fn a_signal_request_and_its_reply_round_trip() {
1882 let request = Request::Signal {
1883 selector: SelectorSpec::Name("web".to_string()),
1884 signal: "SIGHUP".to_string(),
1885 };
1886 let json = serde_json::to_string(&request).unwrap();
1887 assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
1888
1889 let reply = Response::Signalled(vec![
1890 SignalReply {
1891 id: 1,
1892 name: "web".to_string(),
1893 outcome: SignalOutcome::Delivered,
1894 },
1895 SignalReply {
1896 id: 2,
1897 name: "web".to_string(),
1898 outcome: SignalOutcome::NotRunning,
1899 },
1900 SignalReply {
1901 id: 3,
1902 name: "api".to_string(),
1903 outcome: SignalOutcome::Failed {
1904 reason: "no such process".to_string(),
1905 },
1906 },
1907 ]);
1908 let json = serde_json::to_string(&reply).unwrap();
1909 assert_eq!(serde_json::from_str::<Response>(&json).unwrap(), reply);
1910 // The three tags, spelled out: a variant renamed in Rust changes these
1911 // strings mechanically, compiles clean, and breaks a client matching on
1912 // them with nothing to say why.
1913 assert!(json.contains(r#""kind":"delivered""#), "{json}");
1914 assert!(json.contains(r#""kind":"not_running""#), "{json}");
1915 assert!(json.contains(r#""kind":"failed""#), "{json}");
1916 }
1917
1918 /// fails if `Scale` grows a selector. It takes an app NAME, and that is the
1919 /// design: `instances` is a per-app number and instance slots are allocated
1920 /// per name-group, so `shep stock /web.*/ 4` would have to mean either four
1921 /// each or four total and there is no reading of it that is not a guess.
1922 #[test]
1923 fn a_scale_request_names_one_app_and_a_count() {
1924 let request = Request::Scale {
1925 name: "web".to_string(),
1926 count: 4,
1927 };
1928 let json = serde_json::to_string(&request).unwrap();
1929 assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
1930 assert!(json.contains(r#""kind":"scale""#), "{json}");
1931 assert!(json.contains(r#""name":"web""#), "{json}");
1932 // No `selector` key at all — the shape that says this verb is not one of
1933 // the selector-taking family.
1934 assert!(!json.contains("selector"), "{json}");
1935 }
1936
1937 /// fails if `Scaled` stops being distinguishable from the eight other replies
1938 /// carrying a bare `Vec<ProcessInfo>`. Each of those names which request it
1939 /// answers precisely so it can diverge later without a protocol bump — the
1940 /// enum's own doc says not to collapse them, and this is the test that notices.
1941 #[test]
1942 fn a_scaled_reply_carries_its_own_tag() {
1943 let json = serde_json::to_string(&Response::Scaled(vec![])).unwrap();
1944 assert_eq!(json, r#"{"kind":"scaled","data":[]}"#);
1945 }
1946
1947 /// fails if the three outcomes stop being tellable apart on the wire, or if
1948 /// `NotWritten` stops carrying its reason. That reason is the only thing that
1949 /// distinguishes "the app is not reading its stdin" from "the pipe broke", and
1950 /// the operator's next move differs between them.
1951 #[test]
1952 fn a_send_line_request_and_its_reply_round_trip() {
1953 let request = Request::SendLine {
1954 selector: SelectorSpec::Name("repl".to_string()),
1955 line: "reload-config".to_string(),
1956 };
1957 let json = serde_json::to_string(&request).unwrap();
1958 assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
1959
1960 let reply = Response::SentLine(vec![
1961 LineReply {
1962 id: 1,
1963 name: "repl".to_string(),
1964 outcome: LineOutcome::Sent,
1965 },
1966 LineReply {
1967 id: 2,
1968 name: "web".to_string(),
1969 outcome: LineOutcome::NoStdin,
1970 },
1971 LineReply {
1972 id: 3,
1973 name: "stuck".to_string(),
1974 outcome: LineOutcome::NotWritten {
1975 reason: "the app did not read its stdin within 2s".to_string(),
1976 },
1977 },
1978 ]);
1979 let json = serde_json::to_string(&reply).unwrap();
1980 assert_eq!(serde_json::from_str::<Response>(&json).unwrap(), reply);
1981 assert!(json.contains(r#""kind":"sent""#), "{json}");
1982 assert!(json.contains(r#""kind":"no_stdin""#), "{json}");
1983 assert!(json.contains("did not read its stdin"), "{json}");
1984 }
1985
1986 /// fails if a newline can ride inside the line. The wire carries ONE line and
1987 /// the writer appends the terminator, so an embedded newline would deliver two
1988 /// commands where the operator typed one — the shape that turns a typo into an
1989 /// unintended second instruction to a REPL.
1990 #[test]
1991 fn a_line_carrying_a_newline_is_still_one_field_on_the_wire() {
1992 let request = Request::SendLine {
1993 selector: SelectorSpec::All,
1994 line: "a\nb".to_string(),
1995 };
1996 let json = serde_json::to_string(&request).unwrap();
1997 // Escaped, not literal: the frame stays one JSON object. Rejecting it is
1998 // the daemon's job (see `shep whisper`), not serde's, and this pins that
1999 // the wire itself does not quietly split it.
2000 assert!(json.contains(r#""line":"a\nb""#), "{json}");
2001 assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
2002 }
2003
2004 #[test]
2005 fn request_wire_snapshots() {
2006 let requests = vec![
2007 Envelope {
2008 id: 1,
2009 deadline_ms: Some(5000),
2010 body: Request::Ping,
2011 },
2012 Envelope {
2013 id: 2,
2014 deadline_ms: None,
2015 body: Request::ListFlock,
2016 },
2017 Envelope {
2018 id: 3,
2019 deadline_ms: None,
2020 body: Request::Stop {
2021 selector: SelectorSpec::Name("web".to_string()),
2022 },
2023 },
2024 Envelope {
2025 id: 4,
2026 deadline_ms: None,
2027 body: Request::Start {
2028 apps: vec![AppConfig::minimal("web", "./srv")],
2029 },
2030 },
2031 // `All` rather than a named sheep: it is the selector `shep
2032 // reopen` sends when given no argument, and the one a signal can
2033 // ever mean, so it is the row worth pinning.
2034 Envelope {
2035 id: 5,
2036 deadline_ms: None,
2037 body: Request::Reopen {
2038 selector: SelectorSpec::All,
2039 },
2040 },
2041 // Deliberately the same selector as the row above, so the two
2042 // log-plane rows differ by their `kind` and by nothing else: a
2043 // `Flush` that serialized under `reopen`'s tag — the shape a
2044 // copy-pasted variant takes — shows up here as two identical
2045 // objects rather than as a diff a reader has to compare field by
2046 // field. `shep flush` demands an explicit selector, so `all` is
2047 // not a default here the way it is for `reopen`; it is simply the
2048 // widest thing an operator can type.
2049 Envelope {
2050 id: 6,
2051 deadline_ms: None,
2052 body: Request::Flush {
2053 selector: SelectorSpec::All,
2054 },
2055 },
2056 // The same selector as the `stop` row above, for the reason the
2057 // pair above share theirs: `reload` is the third verb that
2058 // demands an explicit selector and replaces what it matches, so
2059 // the variant it would be copy-pasted from is `stop`. Serialized
2060 // under `stop`'s tag it shows up here as two identical objects
2061 // rather than as a diff a reader has to compare field by field.
2062 Envelope {
2063 id: 7,
2064 deadline_ms: None,
2065 body: Request::Reload {
2066 selector: SelectorSpec::Name("web".to_string()),
2067 },
2068 },
2069 // `action`/`params` here match the spec's own §9 example
2070 // (`trigger web set-log-level debug`) and channel.rs's
2071 // with-params fixture verbatim, so a reader tracing a trigger
2072 // from the CLI through the client↔daemon wire to the fd-3 wire
2073 // sees the same two strings at every hop rather than three
2074 // unrelated examples.
2075 Envelope {
2076 id: 8,
2077 deadline_ms: None,
2078 body: Request::Trigger {
2079 selector: SelectorSpec::Name("web".to_string()),
2080 action: "set-log-level".to_string(),
2081 params: Some("debug".to_string()),
2082 },
2083 },
2084 // The first fieldless verb added since `Ping`/`ListFlock`, and
2085 // pinned for that reason: a fieldless variant serializes as a
2086 // bare `{"kind":"..."}` with no `selector` key at all, so a
2087 // reader comparing this row against `stop`'s sees the whole
2088 // difference between the two shapes in one place.
2089 Envelope {
2090 id: 9,
2091 deadline_ms: None,
2092 body: Request::SaveRoll,
2093 },
2094 // Paired with the `save_roll` row above so the two halves of the
2095 // roll — the direction that writes it and the direction that
2096 // assembles from it — sit next to each other, differing by their
2097 // `kind` and by nothing else.
2098 Envelope {
2099 id: 10,
2100 deadline_ms: None,
2101 body: Request::Muster,
2102 },
2103 // The three dog verbs together, in the order an operator meets
2104 // them: ask for a section, start a dog, stop one. Adjacent on
2105 // purpose — `enable_dog` and `disable_dog` differ by their
2106 // `kind` and by `source`, so a `DisableDog` accidentally given
2107 // `EnableDog`'s tag shows up here as two near-identical objects
2108 // rather than as a diff a reader has to compare field by field.
2109 Envelope {
2110 id: 11,
2111 deadline_ms: None,
2112 body: Request::DogConfig {
2113 name: "bark".to_string(),
2114 },
2115 },
2116 Envelope {
2117 id: 12,
2118 deadline_ms: None,
2119 body: Request::EnableDog {
2120 name: "metrics".to_string(),
2121 source: DogSource::BuiltIn,
2122 },
2123 },
2124 Envelope {
2125 id: 13,
2126 deadline_ms: None,
2127 body: Request::DisableDog {
2128 name: "metrics".to_string(),
2129 },
2130 },
2131 // Grouped and adjacent on purpose: `Id`, `Regex` and `Fold` are
2132 // three newtypes over three different inner types, and the wire
2133 // tells them apart only by their own `kind` tag — a `Fold` that
2134 // serialized under `regex`'s tag is a `shep restart fold:api`
2135 // that silently becomes a regex match, which is a wrong set of
2136 // sheep restarted and not an error anyone sees.
2137 Envelope {
2138 id: 14,
2139 deadline_ms: None,
2140 body: Request::Describe {
2141 selector: SelectorSpec::Id(7),
2142 },
2143 },
2144 Envelope {
2145 id: 15,
2146 deadline_ms: None,
2147 body: Request::Describe {
2148 selector: SelectorSpec::Regex("^web-".to_string()),
2149 },
2150 },
2151 Envelope {
2152 id: 16,
2153 deadline_ms: None,
2154 body: Request::Describe {
2155 selector: SelectorSpec::Fold("api".to_string()),
2156 },
2157 },
2158 // `SIGHUP` rather than `SIGTERM`: TERM is what the stop ladder
2159 // already sends, so a fixture using it could not tell a `signal`
2160 // frame from a stop's. HUP is the signal this verb exists for.
2161 Envelope {
2162 id: 17,
2163 deadline_ms: None,
2164 body: Request::Signal {
2165 selector: SelectorSpec::Name("web".to_string()),
2166 signal: "SIGHUP".to_string(),
2167 },
2168 },
2169 // The one verb in this enum whose body has no `selector` key at
2170 // all — a reader comparing this row against `stop`'s sees the
2171 // whole difference in one place.
2172 Envelope {
2173 id: 18,
2174 deadline_ms: None,
2175 body: Request::Scale {
2176 name: "web".to_string(),
2177 count: 4,
2178 },
2179 },
2180 // `SelectorSpec::All` rather than a named sheep, mirroring the
2181 // `reopen`/`flush` rows above: it is the widest thing an operator
2182 // can type, and the line carries no terminator on the wire — the
2183 // shepherd appends it — so a fixture with one proves that half of
2184 // the contract too.
2185 Envelope {
2186 id: 19,
2187 deadline_ms: None,
2188 body: Request::SendLine {
2189 selector: SelectorSpec::All,
2190 line: "reload-config".to_string(),
2191 },
2192 },
2193 // The second verb here with no `selector` key, and the only one
2194 // whose payload a third party writes. Both halves of its
2195 // `Option` are pinned — a paint and a clear — because a dog
2196 // author reading this fixture needs the clear frame's exact
2197 // shape and would otherwise have to guess `null`.
2198 Envelope {
2199 id: 20,
2200 deadline_ms: None,
2201 body: Request::SetSmit {
2202 sheep: "web".to_string(),
2203 smit: Some(
2204 "\u{25b2} main@a1b2c3"
2205 .parse()
2206 .expect("the reference smit is valid"),
2207 ),
2208 },
2209 },
2210 Envelope {
2211 id: 21,
2212 deadline_ms: None,
2213 body: Request::SetSmit {
2214 sheep: "web".to_string(),
2215 smit: None,
2216 },
2217 },
2218 // An EMPTY `apps`, unlike `start`'s row above. The two carry the
2219 // identical payload type, so a second `AppConfig` blob here would
2220 // pin nothing `start`'s blob does not already pin, at fifty lines
2221 // of snapshot. What is genuinely this row's own is the tag and
2222 // the key the list travels under, and an empty list shows both.
2223 Envelope {
2224 id: 22,
2225 deadline_ms: None,
2226 body: Request::ConfigDrift { apps: Vec::new() },
2227 },
2228 // The only STRUCT-shaped `SelectorSpec` variant, and the one
2229 // whose serialized shape moved `PROTOCOL_VERSION` from 1 to 2.
2230 // Every other selector on this wire is a unit or a newtype, both
2231 // already pinned by the rows above, so this row is the only place
2232 // `"kind":"instance"` and the `slot` key are held to anything.
2233 // Without it, renaming the field or flattening the variant turned
2234 // nothing red on the exact type the version bump was for.
2235 Envelope {
2236 id: 23,
2237 deadline_ms: None,
2238 body: Request::Restart {
2239 selector: SelectorSpec::Instance {
2240 name: "web".to_string(),
2241 slot: 2,
2242 },
2243 },
2244 },
2245 // The one request in this enum that an older daemon must never
2246 // be sent, so the one whose exact tag matters most: shep-cli
2247 // gates it on the daemon's crate version, and a rename here
2248 // would be a variant nothing on either side recognises.
2249 Envelope {
2250 id: 24,
2251 deadline_ms: None,
2252 body: Request::HandoverFitness,
2253 },
2254 // The second request gated on the daemon's crate version, and
2255 // pinned beside the first for that reason: the two are asked by
2256 // the same verb, of the two daemons either side of the same
2257 // handover, and a rename of either is a variant nothing on
2258 // either side recognises.
2259 Envelope {
2260 id: 25,
2261 deadline_ms: None,
2262 body: Request::DogStaleness,
2263 },
2264 ];
2265 insta::assert_json_snapshot!("request_wire_v2", requests);
2266 }
2267
2268 #[test]
2269 fn reply_wire_snapshots() {
2270 let replies = vec![
2271 Reply {
2272 id: 1,
2273 result: Ok(Response::Pong),
2274 },
2275 Reply {
2276 id: 2,
2277 result: Ok(Response::Flock(vec![sample_info()])),
2278 },
2279 Reply {
2280 id: 3,
2281 result: Err(RpcError {
2282 code: RpcErrorCode::NotFound,
2283 message: "no sheep matches `web`".to_string(),
2284 daemon_version: None,
2285 }),
2286 },
2287 // Unlike `Reopened`/`Flushed`/`Reloading` above (all wire-identical
2288 // to `Flock`, just under a different `kind` tag, so pinning `Flock`
2289 // once already covers their shape), `Triggered` carries a genuinely
2290 // different row — `ActionReply` is not a `ProcessInfo` — so it earns
2291 // its own entry. `Replied` is the struct-shaped variant of
2292 // `ActionOutcome`, and so the one worth pinning here: the three
2293 // unit variants serialize as bare `{"kind":"..."}`, a shape already
2294 // proven by every fieldless variant elsewhere on this wire.
2295 Reply {
2296 id: 4,
2297 result: Ok(Response::Triggered(vec![ActionReply {
2298 id: 3,
2299 name: "web".to_string(),
2300 outcome: ActionOutcome::Replied {
2301 body: "ok".to_string(),
2302 },
2303 }])),
2304 },
2305 // The only struct-shaped `Response` variant, so the one worth
2306 // pinning here: every other variant on this wire is a newtype
2307 // over a Vec or a unit, both shapes already proven above.
2308 Reply {
2309 id: 5,
2310 result: Ok(Response::RollSaved {
2311 path: "/home/ada/.shep/flock.json".to_string(),
2312 apps: 2,
2313 }),
2314 },
2315 // `sample_info()` above pins the absent marker (a sheep's
2316 // `"dog": null`); this row is the only place the present one is
2317 // pinned, and `Adopted` rather than `BuiltIn` because it is the
2318 // variant carrying a payload — the unit variant's shape is
2319 // already proven by every fieldless variant on this wire.
2320 Reply {
2321 id: 6,
2322 result: Ok(Response::Flock(vec![ProcessInfo {
2323 id: 7,
2324 name: "otel".to_string(),
2325 dog: Some(DogSource::Adopted {
2326 path: "/usr/local/bin/shep-otel".to_string(),
2327 }),
2328 ..sample_info()
2329 }])),
2330 },
2331 // The opaque blob, pinned as a blob: the daemon renders a TOML
2332 // table into a string and never a typed structure, so what this
2333 // row proves is that the section crosses the wire as text.
2334 Reply {
2335 id: 7,
2336 result: Ok(Response::DogSection {
2337 toml: "port = 9615\n".to_string().into(),
2338 }),
2339 },
2340 // The only `Response` variant carrying a BARE `ProcessInfo`
2341 // rather than a `Vec` of them: `enable` starts exactly one dog,
2342 // and a one-element list would invite a reader to wonder when it
2343 // holds two.
2344 Reply {
2345 id: 8,
2346 result: Ok(Response::DogStarted(ProcessInfo {
2347 id: 4,
2348 name: "metrics".to_string(),
2349 dog: Some(DogSource::BuiltIn),
2350 ..sample_info()
2351 })),
2352 },
2353 // The existing comment on the `Triggered` row is right that pinning
2354 // `Flock` once already proves the `Vec<ProcessInfo>` SHAPE — but
2355 // it does not prove any of these variants' own `kind` tags, and
2356 // three of them are not `Vec<ProcessInfo>`-shaped at all
2357 // (`Deleted` is a `Vec<u32>`, `Subscribed` and `ShuttingDown`
2358 // carry nothing). Each row below therefore carries the smallest
2359 // body that shows its wire shape — empty where empty is legal,
2360 // `Deleted`'s two ids where the shape needs elements: what is
2361 // being pinned here is the tag, and a body repeated eight times
2362 // would bury it.
2363 Reply {
2364 id: 9,
2365 result: Ok(Response::Described(vec![])),
2366 },
2367 Reply {
2368 id: 10,
2369 result: Ok(Response::Started(vec![])),
2370 },
2371 Reply {
2372 id: 11,
2373 result: Ok(Response::Stopped(vec![])),
2374 },
2375 Reply {
2376 id: 12,
2377 result: Ok(Response::Restarted(vec![])),
2378 },
2379 Reply {
2380 id: 13,
2381 result: Ok(Response::Reloading(vec![])),
2382 },
2383 Reply {
2384 id: 14,
2385 result: Ok(Response::Deleted(vec![7, 8])),
2386 },
2387 Reply {
2388 id: 15,
2389 result: Ok(Response::Reopened(vec![])),
2390 },
2391 Reply {
2392 id: 16,
2393 result: Ok(Response::Flushed(vec![])),
2394 },
2395 Reply {
2396 id: 17,
2397 result: Ok(Response::Mustered(vec![])),
2398 },
2399 Reply {
2400 id: 18,
2401 result: Ok(Response::Subscribed),
2402 },
2403 Reply {
2404 id: 19,
2405 result: Ok(Response::ShuttingDown),
2406 },
2407 // `Signalled`, mirroring the `Triggered` row above: three rows,
2408 // one per `SignalOutcome` variant, so a reader sees the whole
2409 // shape of the reply in one pinned fixture rather than one row
2410 // that happens to hit `Delivered` and leaves the other two tags
2411 // unproven.
2412 Reply {
2413 id: 20,
2414 result: Ok(Response::Signalled(vec![
2415 SignalReply {
2416 id: 1,
2417 name: "web".to_string(),
2418 outcome: SignalOutcome::Delivered,
2419 },
2420 SignalReply {
2421 id: 2,
2422 name: "web".to_string(),
2423 outcome: SignalOutcome::NotRunning,
2424 },
2425 SignalReply {
2426 id: 3,
2427 name: "api".to_string(),
2428 outcome: SignalOutcome::Failed {
2429 reason: "no such process".to_string(),
2430 },
2431 },
2432 ])),
2433 },
2434 Reply {
2435 id: 21,
2436 result: Ok(Response::Scaled(vec![sample_info()])),
2437 },
2438 // `SentLine`, mirroring the `Signalled` row above: three rows, one
2439 // per `LineOutcome` variant, so a reader sees the whole shape of
2440 // the reply in one pinned fixture rather than one row that
2441 // happens to hit `Sent` and leaves the other two tags unproven.
2442 Reply {
2443 id: 22,
2444 result: Ok(Response::SentLine(vec![
2445 LineReply {
2446 id: 1,
2447 name: "repl".to_string(),
2448 outcome: LineOutcome::Sent,
2449 },
2450 LineReply {
2451 id: 2,
2452 name: "web".to_string(),
2453 outcome: LineOutcome::NoStdin,
2454 },
2455 LineReply {
2456 id: 3,
2457 name: "stuck".to_string(),
2458 outcome: LineOutcome::NotWritten {
2459 reason: "the app did not read its stdin within 2s".to_string(),
2460 },
2461 },
2462 ])),
2463 },
2464 // A `Described` row with a real lamb tree. The `null` shape is pinned
2465 // on every other row here; this is the one that pins what a walked
2466 // sheep serializes as, which is the shape a `describe` consumer
2467 // actually parses.
2468 Reply {
2469 id: 23,
2470 result: Ok(Response::Described(vec![
2471 ProcessInfo::builder(3, "web", ProcStatus::Online)
2472 .pid(Some(4242))
2473 .lambs(Some(vec![Lamb::new(4243, "node"), Lamb::new(4244, "sh")]))
2474 .build(),
2475 ])),
2476 },
2477 // `sample_info()` pins `last_exit`'s "exited normally" shape
2478 // (`code` set, `signal` absent) on every row above; this is the
2479 // only place the other one — killed by a signal, `code` absent
2480 // — is pinned. `SIGTERM`'s raw number (15) rather than a
2481 // symbolic one, because [`ExitInfo::signal`]'s own doc says this
2482 // crate carries no name for it; naming one is a job for
2483 // whichever OS-aware layer renders this field.
2484 Reply {
2485 id: 24,
2486 result: Ok(Response::Flock(vec![
2487 ProcessInfo::builder(5, "worker", ProcStatus::Stopped)
2488 .restarts(1)
2489 .last_exit(Some(ExitInfo {
2490 code: None,
2491 signal: Some(15),
2492 }))
2493 .build(),
2494 ])),
2495 },
2496 // The one row that pins a smit on the wire. `sample_info()`
2497 // carries none, deliberately (see `every_setter_writes_its_own_
2498 // field_and_no_other` for why it cannot), so without this row
2499 // the field is pinned only in its absent shape — and the absent
2500 // shape is not the one a dog's reader has to parse.
2501 Reply {
2502 id: 25,
2503 result: Ok(Response::SmitPainted(vec![
2504 ProcessInfo::builder(3, "web", ProcStatus::Online)
2505 .pid(Some(4242))
2506 .smit(Some("\u{25b2} main@a1b2c3".to_string()))
2507 .build(),
2508 ])),
2509 },
2510 // Two entries in one reply, and each is the shape the other is
2511 // not: a sheep drifting in one field and a sheep drifting in
2512 // several. `env` is deliberately one of them, because reporting
2513 // it as a bare NAME is the whole security property of this row
2514 // (IR-41) and a fixture is where an out-of-tree reader learns
2515 // that no value ever travels with it.
2516 Reply {
2517 id: 26,
2518 result: Ok(Response::Drifted(vec![
2519 SheepDrift::new("web", vec!["cwd".to_string()]),
2520 SheepDrift::new(
2521 "api",
2522 vec!["args".to_string(), "env".to_string(), "script".to_string()],
2523 ),
2524 ])),
2525 },
2526 // `sample_info()` pins `instance`'s absent shape (`None`, an old
2527 // peer or a single-instance app); every row above reuses it, so
2528 // without this row the present shape (`Some(2)`, a live slot on
2529 // a scaled app) is never on the wire at all.
2530 Reply {
2531 id: 27,
2532 result: Ok(Response::Flock(vec![
2533 ProcessInfo::builder(9, "web", ProcStatus::Online)
2534 .pid(Some(5150))
2535 .instance(Some(2))
2536 .build(),
2537 ])),
2538 },
2539 // Both shapes of the handover answer, because the difference
2540 // between them is a `null` and a caller that read the key's
2541 // presence rather than its value would pass on one and refuse
2542 // every flock on the other.
2543 Reply {
2544 id: 28,
2545 result: Ok(Response::HandoverFitness { refusal: None }),
2546 },
2547 Reply {
2548 id: 29,
2549 result: Ok(Response::HandoverFitness {
2550 refusal: Some("sheep 'web' has a shepherd channel".to_string()),
2551 }),
2552 },
2553 // Both lists non-empty and DIFFERENT, because the two carry the
2554 // same wire shape and a reply that filled one from the other
2555 // would be invisible in a fixture that used the same names
2556 // twice. Empty is the shape an ordinary reload sees, and it is
2557 // already proven by every `Vec`-carrying row above.
2558 Reply {
2559 id: 30,
2560 result: Ok(Response::DogStaleness {
2561 stale: vec!["metrics".to_string()],
2562 pending: vec!["bark".to_string()],
2563 }),
2564 },
2565 // `sample_info()` pins `handshook`'s absent shape (`None`, a
2566 // sheep or an older peer); every row above reuses it, so
2567 // without this row the shape that actually changes an
2568 // operator's reading — a dog whose process is up and which has
2569 // never answered this shepherd — is never on the wire at all.
2570 //
2571 // `dog_stale: false` is not padding: this is the silence the
2572 // shepherd is still waiting out, and the row below is the one it
2573 // has given up on. The two differ in exactly one byte-level key
2574 // and in what every operator-facing surface must say about them,
2575 // so pinning one without the other would leave the distinction
2576 // untested on the wire it travels over.
2577 Reply {
2578 id: 31,
2579 result: Ok(Response::Flock(vec![
2580 ProcessInfo::builder(10, "log-rotate", ProcStatus::Online)
2581 .pid(Some(208_341))
2582 .dog(Some(DogSource::Adopted {
2583 path: "/usr/local/bin/shep-log-rotate".to_string(),
2584 }))
2585 .handshook(Some(false))
2586 .dog_stale(Some(false))
2587 .build(),
2588 ])),
2589 },
2590 Reply {
2591 id: 32,
2592 result: Ok(Response::Flock(vec![
2593 ProcessInfo::builder(10, "log-rotate", ProcStatus::Online)
2594 .pid(Some(208_341))
2595 .dog(Some(DogSource::Adopted {
2596 path: "/usr/local/bin/shep-log-rotate".to_string(),
2597 }))
2598 .handshook(Some(false))
2599 .dog_stale(Some(true))
2600 .build(),
2601 ])),
2602 },
2603 ];
2604 insta::assert_json_snapshot!("reply_wire_v2", replies);
2605 }
2606
2607 /// fails if the new field breaks an older peer, on the same terms as
2608 /// `last_exit` and `lambs` before it. A daemon that predates smits sends
2609 /// no `smit` key, and this decoding to `None` rather than erroring is
2610 /// what keeps `PROTOCOL_VERSION` at 2 rather than needing another bump.
2611 #[test]
2612 fn a_process_info_without_a_smit_key_still_deserializes() {
2613 let fixture = r#"{"id":1,"name":"web","status":"online","pid":42,"restarts":0,"uptime_ms":10,"fold":null,"out_file":null,"err_file":null,"cpu_percent":null,"memory_bytes":null,"dog":null,"lambs":null,"last_exit":null}"#;
2614 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2615 assert_eq!(info.smit, None);
2616 }
2617
2618 /// fails if `handshook` breaks an older peer, on the same terms as
2619 /// `smit` and `instance` before it. A daemon that predates the field
2620 /// sends no `handshook` key and still announces protocol 2, so this
2621 /// decoding to `None` rather than erroring is what keeps
2622 /// `PROTOCOL_VERSION` at 2: the evolution rule in this module's parent
2623 /// says an additive optional field keeps the version, and a required
2624 /// one would make a current client unable to list against that daemon
2625 /// at all.
2626 ///
2627 /// The fixture is a DOG's row, deliberately — that is the one row where
2628 /// the missing key changes what a renderer prints, and `None` there has
2629 /// to keep meaning "render this exactly as it rendered before the field
2630 /// existed" rather than "this dog has never handshaken".
2631 #[test]
2632 fn a_process_info_without_a_handshook_key_still_deserializes() {
2633 let fixture = r#"{"id":1,"name":"metrics","status":"online","pid":42,"restarts":0,"uptime_ms":10,"fold":null,"out_file":null,"err_file":null,"cpu_percent":null,"memory_bytes":null,"dog":{"kind":"built_in"},"lambs":null,"last_exit":null,"smit":null,"instance":0}"#;
2634 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2635 assert_eq!(info.handshook, None);
2636 assert_eq!(info.dog, Some(DogSource::BuiltIn));
2637 }
2638
2639 /// fails if `dog_stale` breaks an older peer, on the same terms as
2640 /// `handshook` before it -- the same additive-optional rule, the same
2641 /// unchanged `PROTOCOL_VERSION`.
2642 ///
2643 /// The fixture carries `handshook: false`, which is the case that
2644 /// matters. A shepherd old enough to report a dog silent but too old to
2645 /// say whether it gave up on that dog must keep rendering exactly the
2646 /// word it rendered before -- `None` here is "this shepherd has no
2647 /// verdict to report", never "it has not given up".
2648 #[test]
2649 fn a_process_info_without_a_dog_stale_key_still_deserializes() {
2650 let fixture = r#"{"id":1,"name":"metrics","status":"online","pid":42,"restarts":0,"uptime_ms":10,"fold":null,"out_file":null,"err_file":null,"cpu_percent":null,"memory_bytes":null,"dog":{"kind":"built_in"},"lambs":null,"last_exit":null,"smit":null,"instance":0,"handshook":false}"#;
2651 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2652 assert_eq!(info.dog_stale, None);
2653 assert_eq!(info.handshook, Some(false));
2654 }
2655
2656 /// fails if the daemon accepts a smit it should refuse. [`Smit`] must
2657 /// validate on the way IN, not only in `FromStr`: `docs/dogs.md` tells
2658 /// dog authors to speak this wire directly, so a dog written in another
2659 /// language never runs our parser.
2660 #[test]
2661 fn a_smit_is_validated_when_it_is_deserialized_not_only_when_parsed() {
2662 for bad in [
2663 r#""\u001b[2Jgone""#.to_string(), // an escape
2664 r#""a\nb""#.to_string(), // a newline
2665 r#""""#.to_string(), // empty
2666 r#"" ""#.to_string(), // whitespace
2667 format!(r#""{}""#, "x".repeat(Smit::MAX_CHARS + 1)), // too long
2668 ] {
2669 assert!(
2670 serde_json::from_str::<Smit>(&bad).is_err(),
2671 "a daemon must refuse this on the wire: {bad}"
2672 );
2673 }
2674 assert!(serde_json::from_str::<Smit>(r#""\u25b2 main@a1b2c3""#).is_ok());
2675 }
2676
2677 /// fails if a smit stops travelling as a bare JSON string. It is a
2678 /// newtype with a hand-written `Deserialize`, and the pair only agrees
2679 /// with itself if the serialize side stays transparent — a `Smit` that
2680 /// serialized as `{"0":"..."}` would round-trip through nothing.
2681 #[test]
2682 fn a_smit_travels_as_a_bare_string() {
2683 let smit: Smit = "\u{25b2} main@a1b2c3".parse().expect("valid");
2684 let json = serde_json::to_string(&smit).unwrap();
2685 assert_eq!(json, "\"\u{25b2} main@a1b2c3\"");
2686 assert_eq!(serde_json::from_str::<Smit>(&json).unwrap(), smit);
2687 }
2688
2689 /// fails if the cap starts counting bytes or display columns. Forty-eight
2690 /// CJK characters are 144 bytes and roughly 96 columns, and all three
2691 /// numbers disagree — a byte cap would refuse this legitimate smit at a
2692 /// third of its apparent length.
2693 #[test]
2694 fn a_smit_is_capped_in_characters_not_bytes() {
2695 let cjk = "\u{7f8a}".repeat(Smit::MAX_CHARS);
2696 assert_eq!(cjk.len(), Smit::MAX_CHARS * 3);
2697 assert!(cjk.parse::<Smit>().is_ok(), "{cjk}");
2698 assert_eq!(
2699 "x".repeat(Smit::MAX_CHARS + 1).parse::<Smit>(),
2700 Err(SmitError::TooLong {
2701 chars: Smit::MAX_CHARS + 1
2702 })
2703 );
2704 }
2705
2706 /// fails if a smit is repaired rather than refused. Trimming or stripping
2707 /// would hand an operator a mark its publisher never sent, and would put
2708 /// shep in the business of editing a string it has agreed not to
2709 /// understand.
2710 #[test]
2711 fn a_smit_is_stored_exactly_as_it_arrived() {
2712 let padded: Smit = " main@a1b2c3 ".parse().expect("valid");
2713 assert_eq!(padded.as_str(), " main@a1b2c3 ");
2714 assert_eq!(padded.to_string(), " main@a1b2c3 ");
2715 }
2716
2717 #[test]
2718 fn v1_fixture_still_deserializes() {
2719 // Committed byte fixture from protocol v1 — if this breaks, bump
2720 // PROTOCOL_VERSION and record it in the CHANGELOG (IR-35).
2721 let fixture = r#"{"id":7,"deadline_ms":null,"body":{"kind":"stop","selector":{"kind":"name","value":"web"}}}"#;
2722 let env: Envelope = serde_json::from_str(fixture).unwrap();
2723 assert_eq!(env.id, 7);
2724 assert!(matches!(
2725 env.body,
2726 Request::Stop { selector: SelectorSpec::Name(ref n) } if n == "web"
2727 ));
2728 }
2729
2730 #[test]
2731 fn hello_handshake_shape() {
2732 let hello = Hello {
2733 client_version: "0.1.0".to_string(),
2734 protocol: PROTOCOL_VERSION,
2735 dog_name: None,
2736 };
2737 let json = serde_json::to_string(&hello).unwrap();
2738 assert_eq!(json, r#"{"client_version":"0.1.0","protocol":2}"#);
2739 }
2740
2741 /// fails if a non-dog client's `Hello` grows a key. The CLI is the
2742 /// overwhelming majority of handshakes and sends `dog_name: None`, so
2743 /// `skip_serializing_if` is what keeps this addition free on the wire
2744 /// for every client that is not a dog — and what makes the bytes above
2745 /// byte-identical to the ones protocol 2 shipped with.
2746 #[test]
2747 fn a_dogs_hello_names_the_dog_and_nothing_elses_does() {
2748 let dog = Hello {
2749 client_version: "0.1.0".to_string(),
2750 protocol: PROTOCOL_VERSION,
2751 dog_name: Some("metrics".to_string()),
2752 };
2753 let json = serde_json::to_string(&dog).unwrap();
2754 assert_eq!(
2755 json,
2756 r#"{"client_version":"0.1.0","protocol":2,"dog_name":"metrics"}"#
2757 );
2758 assert_eq!(serde_json::from_str::<Hello>(&json).unwrap(), dog);
2759 }
2760
2761 /// fails if `Hello` gains `#[serde(deny_unknown_fields)]`, or if
2762 /// `dog_name` stops being optional — the two ways this addition could
2763 /// become a wire break after the fact.
2764 ///
2765 /// `Hello` is the version-negotiation frame, which makes it the one
2766 /// place where rejecting an unknown field would be unrecoverable: the
2767 /// daemon would refuse a newer client BEFORE reading `protocol`, so
2768 /// neither peer could report the skew that caused it. The fixture below
2769 /// is the committed bytes a client built before this field sends
2770 /// (IR-35), and the second half is the same rule in the other
2771 /// direction — an older daemon parsing a newer client's frame.
2772 #[test]
2773 fn a_hello_without_a_dog_name_still_parses() {
2774 let fixture = r#"{"client_version":"0.1.14","protocol":2}"#;
2775 let hello: Hello = serde_json::from_str(fixture).unwrap();
2776 assert_eq!(hello.protocol, 2);
2777 assert_eq!(hello.dog_name, None);
2778
2779 // The other direction: whatever an older daemon does not know, it
2780 // must ignore rather than refuse. `unknown_to_an_older_daemon`
2781 // stands in for `dog_name` as that daemon would see it.
2782 let newer = r#"{"client_version":"9.9.9","protocol":2,"dog_name":"metrics","unknown_to_an_older_daemon":true}"#;
2783 let hello: Hello = serde_json::from_str(newer).unwrap();
2784 assert_eq!(hello.protocol, 2);
2785 assert_eq!(hello.dog_name.as_deref(), Some("metrics"));
2786 }
2787
2788 #[test]
2789 fn hello_reply_carries_typed_skew_error() {
2790 let refusal: HelloReply = Err(RpcError {
2791 code: RpcErrorCode::ProtocolMismatch,
2792 message: "daemon speaks protocol 1, client sent 2".to_string(),
2793 daemon_version: None,
2794 });
2795 let json = serde_json::to_string(&refusal).unwrap();
2796 assert_eq!(
2797 json,
2798 r#"{"Err":{"code":"protocol_mismatch","message":"daemon speaks protocol 1, client sent 2"}}"#
2799 );
2800 let back: HelloReply = serde_json::from_str(&json).unwrap();
2801 assert_eq!(back, refusal);
2802 }
2803
2804 #[test]
2805 fn v1_reply_fixture_still_deserializes() {
2806 // Committed byte fixture, protocol v1 (IR-35).
2807 let ok = r#"{"id":1,"result":{"Ok":{"kind":"pong"}}}"#;
2808 let reply: Reply = serde_json::from_str(ok).unwrap();
2809 assert!(matches!(reply.result, Ok(Response::Pong)));
2810 let err = r#"{"id":2,"result":{"Err":{"code":"not_found","message":"no sheep"}}}"#;
2811 let reply: Reply = serde_json::from_str(err).unwrap();
2812 assert_eq!(reply.result.unwrap_err().code, RpcErrorCode::NotFound);
2813 }
2814
2815 #[test]
2816 fn v1_hello_ack_fixture_still_deserializes() {
2817 let fixture = r#"{"Ok":{"daemon_version":"0.1.0","protocol":1,"pid":4242}}"#;
2818 let ack: HelloReply = serde_json::from_str(fixture).unwrap();
2819 assert_eq!(ack.unwrap().pid, 4242);
2820 }
2821
2822 /// fails if the two fields stop being optional. A daemon built before
2823 /// them sends a reply with no such keys, and both peers still announce
2824 /// protocol 1 — a required field would make a current client unable to
2825 /// list against that daemon at all.
2826 #[test]
2827 fn v1_process_info_without_stats_still_deserializes() {
2828 let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend","out_file":"/l/o.log","err_file":"/l/e.log"}"#;
2829 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2830 assert_eq!(info.cpu_percent, None);
2831 assert_eq!(info.memory_bytes, None);
2832 }
2833
2834 #[test]
2835 fn v1_process_info_without_log_paths_still_deserializes() {
2836 // Committed byte fixture from before `out_file`/`err_file` existed
2837 // (IR-35). The handshake only compares PROTOCOL_VERSION, which this
2838 // addition deliberately did not bump, so a daemon built at this
2839 // vintage still connects to a current client and sends exactly these
2840 // bytes. Absent keys must land as `None`, not as a decode error.
2841 let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend"}"#;
2842 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2843 assert_eq!(info.id, 3);
2844 assert_eq!(info.out_file, None);
2845 assert_eq!(info.err_file, None);
2846 }
2847
2848 #[test]
2849 fn an_old_client_still_decodes_a_new_process_info() {
2850 // The other skew direction: a client built before the fields reads a
2851 // current daemon's reply. `ProcessInfo` carries no
2852 // `deny_unknown_fields` (unlike the config types in
2853 // `crate::config`), so the two extra keys are ignored rather than
2854 // refused — which is what makes this addition version-preserving.
2855 #[derive(Deserialize)]
2856 struct V1ProcessInfo {
2857 id: u32,
2858 fold: Option<String>,
2859 }
2860
2861 let current = serde_json::to_string(&sample_info()).unwrap();
2862 let old: V1ProcessInfo = serde_json::from_str(¤t).unwrap();
2863 assert_eq!(old.id, 3);
2864 assert_eq!(old.fold.as_deref(), Some("backend"));
2865 }
2866
2867 #[test]
2868 fn an_rpc_error_without_a_daemon_version_serializes_exactly_as_before() {
2869 // `skip_serializing_if` is what makes this addition free: a daemon
2870 // with nothing to say puts the same bytes on the wire it always did,
2871 // not a `"daemon_version":null` key an older client would have to
2872 // ignore. Pinned as an exact string, because "additive" is a claim
2873 // about bytes.
2874 let plain = RpcError {
2875 code: RpcErrorCode::NotFound,
2876 message: "no sheep".to_string(),
2877 daemon_version: None,
2878 };
2879 assert_eq!(
2880 serde_json::to_string(&plain).unwrap(),
2881 r#"{"code":"not_found","message":"no sheep"}"#
2882 );
2883 }
2884
2885 #[test]
2886 fn a_v1_rpc_error_fixture_deserializes_with_no_daemon_version() {
2887 // Committed byte fixture from before this field existed (IR-35): the
2888 // skew direction that matters, a CURRENT client reading an OLD
2889 // daemon's refusal. It must read as `None` rather than failing to
2890 // decode, or the field breaks the upgrade it exists to smooth.
2891 let fixture =
2892 r#"{"code":"protocol_mismatch","message":"daemon speaks protocol 1, client sent 2"}"#;
2893 let err: RpcError = serde_json::from_str(fixture).unwrap();
2894 assert_eq!(err.code, RpcErrorCode::ProtocolMismatch);
2895 assert_eq!(err.daemon_version, None);
2896 }
2897
2898 #[test]
2899 fn an_old_client_ignores_an_rpc_error_field_it_has_never_seen() {
2900 // Step 1 of the handover work: proof that `RpcError` may grow an
2901 // optional field WITHOUT moving `PROTOCOL_VERSION`. Like
2902 // `ProcessInfo` above, `RpcError` carries no `deny_unknown_fields`,
2903 // so a client built before a field decodes a daemon that sends it
2904 // rather than failing the handshake on it.
2905 #[derive(Deserialize)]
2906 struct OldRpcError {
2907 code: RpcErrorCode,
2908 message: String,
2909 }
2910
2911 let current = serde_json::to_string(&RpcError {
2912 code: RpcErrorCode::ProtocolMismatch,
2913 message: "daemon speaks protocol 1, client sent 2".to_string(),
2914 daemon_version: Some("0.1.16".to_string()),
2915 })
2916 .unwrap();
2917 let old: OldRpcError = serde_json::from_str(¤t).expect("must tolerate");
2918 assert_eq!(old.code, RpcErrorCode::ProtocolMismatch);
2919 assert_eq!(old.message, "daemon speaks protocol 1, client sent 2");
2920 }
2921
2922 #[test]
2923 fn deadline_exceeded_code_serializes_snake_case() {
2924 // Additive variant (evolution rule): the existing codes keep their
2925 // strings, so v1 byte fixtures above still deserialize unchanged.
2926 assert_eq!(
2927 serde_json::to_string(&RpcErrorCode::DeadlineExceeded).unwrap(),
2928 "\"deadline_exceeded\""
2929 );
2930 assert_eq!(
2931 serde_json::from_str::<RpcErrorCode>("\"deadline_exceeded\"").unwrap(),
2932 RpcErrorCode::DeadlineExceeded
2933 );
2934 }
2935
2936 #[test]
2937 fn action_outcome_kinds_serialize_snake_case_and_round_trip() {
2938 // The shared snapshots above exercise exactly one `ActionOutcome`
2939 // variant (`Replied`, the only struct-shaped one, in
2940 // `reply_wire_snapshots`) — nothing else there would catch a rename
2941 // of `no_channel`, `skipped`, or `timed_out`. Pinned here instead,
2942 // the same way `deadline_exceeded_code_serializes_snake_case` pins a
2943 // lone `RpcErrorCode` variant above.
2944 let cases = [
2945 (
2946 ActionOutcome::Replied {
2947 body: "pong".to_string(),
2948 },
2949 r#"{"kind":"replied","body":"pong"}"#,
2950 ),
2951 (ActionOutcome::NoChannel, r#"{"kind":"no_channel"}"#),
2952 (ActionOutcome::Skipped, r#"{"kind":"skipped"}"#),
2953 (ActionOutcome::TimedOut, r#"{"kind":"timed_out"}"#),
2954 ];
2955 for (outcome, wire) in cases {
2956 assert_eq!(
2957 serde_json::to_string(&outcome).unwrap(),
2958 wire,
2959 "{outcome:?}"
2960 );
2961 assert_eq!(
2962 serde_json::from_str::<ActionOutcome>(wire).unwrap(),
2963 outcome
2964 );
2965 }
2966 }
2967
2968 /// fails if `SaveRoll` or `RollSaved` is given a `rename`, or if
2969 /// `Response`'s `content = "data"` is dropped — either changes these two
2970 /// strings while every type-level test in this module keeps passing.
2971 #[test]
2972 fn save_roll_serializes_snake_case_with_its_payload_under_data() {
2973 assert_eq!(
2974 serde_json::to_string(&Request::SaveRoll).unwrap(),
2975 r#"{"kind":"save_roll"}"#
2976 );
2977 let reply = Response::RollSaved {
2978 path: "/tmp/flock.json".to_string(),
2979 apps: 3,
2980 };
2981 let wire = r#"{"kind":"roll_saved","data":{"path":"/tmp/flock.json","apps":3}}"#;
2982 assert_eq!(serde_json::to_string(&reply).unwrap(), wire);
2983 assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), reply);
2984 }
2985
2986 /// fails if `Muster` or `Mustered` is given a `rename`, or if `Mustered`
2987 /// is declared fieldless — any of the three changes one of these two
2988 /// strings while every type-level test in this module keeps passing.
2989 ///
2990 /// The listing is empty on purpose. `Mustered` carries the same
2991 /// `Vec<ProcessInfo>` `Flock` does, and `reply_wire_snapshots` already
2992 /// pins that row field by field; what is unpinned until here is this
2993 /// variant's own tag and whether its payload lands under `data` at all.
2994 #[test]
2995 fn muster_serializes_snake_case_with_its_listing_under_data() {
2996 assert_eq!(
2997 serde_json::to_string(&Request::Muster).unwrap(),
2998 r#"{"kind":"muster"}"#
2999 );
3000 let reply = Response::Mustered(Vec::new());
3001 let wire = r#"{"kind":"mustered","data":[]}"#;
3002 assert_eq!(serde_json::to_string(&reply).unwrap(), wire);
3003 assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), reply);
3004 }
3005
3006 /// fails if any of the three verbs or either reply is given a `rename`,
3007 /// or if `Response`'s `content = "data"` is dropped. `disable_dog`'s
3008 /// answer is `Deleted`, which no other test in this module pairs with
3009 /// this verb — a handler wired to answer `Deleted` for `EnableDog` would
3010 /// still round-trip, and this is where the pairing is written down.
3011 #[test]
3012 fn the_dog_verbs_serialize_snake_case_with_their_payloads_under_data() {
3013 assert_eq!(
3014 serde_json::to_string(&Request::DogConfig {
3015 name: "bark".to_string()
3016 })
3017 .unwrap(),
3018 r#"{"kind":"dog_config","name":"bark"}"#
3019 );
3020 assert_eq!(
3021 serde_json::to_string(&Request::DisableDog {
3022 name: "bark".to_string()
3023 })
3024 .unwrap(),
3025 r#"{"kind":"disable_dog","name":"bark"}"#
3026 );
3027 let section = Response::DogSection {
3028 toml: "port = 9615\n".to_string().into(),
3029 };
3030 let wire = r#"{"kind":"dog_section","data":{"toml":"port = 9615\n"}}"#;
3031 assert_eq!(serde_json::to_string(§ion).unwrap(), wire);
3032 assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), section);
3033 }
3034
3035 #[test]
3036 fn dog_section_toml_debug_does_not_leak() {
3037 // IR-41: a dog's `[dog.<name>]` section routinely holds webhook
3038 // credentials (a Discord/Slack URL with a bearer token embedded).
3039 // `Response` derives `Debug`, so this is the one thing standing
3040 // between that token and any future `tracing::debug!("{:?}", reply)`.
3041 // Exact string pinned so a lazy `#[derive(Debug)]` refactor on
3042 // `DogSectionToml` fails this test instead of silently reopening
3043 // the leak.
3044 let toml: DogSectionToml =
3045 "webhook_url = \"https://discord.com/api/webhooks/1/super-secret-token\"\n"
3046 .to_string()
3047 .into();
3048 assert_eq!(format!("{toml:?}"), "DogSectionToml(<70 bytes>)");
3049
3050 let response = Response::DogSection { toml };
3051 assert_eq!(
3052 format!("{response:?}"),
3053 "DogSection { toml: DogSectionToml(<70 bytes>) }"
3054 );
3055 }
3056
3057 /// The fixture is built so the two candidate orders CANNOT agree: read
3058 /// by id it is `web/1, api/2, web/0`, read by name it is
3059 /// `api, web, web`. A listing that happened to be alphabetical already,
3060 /// or whose ids happened to ascend with its names, would pass under
3061 /// either rule and prove nothing.
3062 ///
3063 /// The two `web` rows are the tiebreak half, and they are the reason a
3064 /// multi-instance fixture is required: their ids are seeded out of order
3065 /// (1 before 0), so a sort keyed on name alone would leave them as it
3066 /// found them and fail the last assertion while passing the first.
3067 #[test]
3068 fn a_listing_sorts_by_name_then_by_id() {
3069 let mut listing = vec![
3070 ProcessInfo::builder(1, "web", ProcStatus::Online).build(),
3071 ProcessInfo::builder(2, "api", ProcStatus::Online).build(),
3072 ProcessInfo::builder(0, "web", ProcStatus::Online).build(),
3073 ];
3074 sort_flock(&mut listing);
3075
3076 let seen: Vec<(&str, u32)> = listing
3077 .iter()
3078 .map(|info| (info.name.as_str(), info.id))
3079 .collect();
3080 assert_eq!(
3081 seen,
3082 vec![("api", 2), ("web", 0), ("web", 1)],
3083 "name first, then id inside a name"
3084 );
3085 }
3086
3087 #[test]
3088 fn an_instance_slot_survives_a_round_trip_and_defaults_to_absent() {
3089 let with = ProcessInfo::builder(1, "web", ProcStatus::Online)
3090 .instance(Some(2))
3091 .build();
3092 assert_eq!(with.instance, Some(2));
3093
3094 let without = ProcessInfo::builder(1, "web", ProcStatus::Online).build();
3095 assert_eq!(
3096 without.instance, None,
3097 "a row nobody set a slot on says so, rather than claiming slot 0"
3098 );
3099 }
3100
3101 #[test]
3102 fn a_reply_from_a_daemon_without_the_field_deserializes_as_absent() {
3103 // The skew case the Option exists for: an older shepherd's JSON has no
3104 // `instance` key at all.
3105 let json = r#"{"id":1,"name":"web","status":"online","pid":null,
3106 "restarts":0,"uptime_ms":0,"fold":null,"out_file":null,
3107 "err_file":null,"cpu_percent":null,"memory_bytes":null,"dog":null,
3108 "lambs":null,"last_exit":null,"smit":null}"#;
3109 let info: ProcessInfo = serde_json::from_str(json).expect("older reply still parses");
3110 assert_eq!(info.instance, None);
3111 }
3112
3113 #[test]
3114 fn sort_flock_orders_by_slot_before_id() {
3115 // A reload gave slot 0 a fresh, higher id. Slot order must still win.
3116 let mut listing = vec![
3117 ProcessInfo::builder(9, "web", ProcStatus::Online)
3118 .instance(Some(0))
3119 .build(),
3120 ProcessInfo::builder(2, "web", ProcStatus::Online)
3121 .instance(Some(1))
3122 .build(),
3123 ];
3124 sort_flock(&mut listing);
3125 assert_eq!(
3126 listing.iter().map(|i| i.id).collect::<Vec<_>>(),
3127 vec![9, 2],
3128 "slot 0 leads even though its id is higher"
3129 );
3130 }
3131
3132 #[test]
3133 fn sort_flock_falls_back_to_id_when_no_row_carries_a_slot() {
3134 let mut listing = vec![
3135 ProcessInfo::builder(5, "web", ProcStatus::Online).build(),
3136 ProcessInfo::builder(3, "web", ProcStatus::Online).build(),
3137 ];
3138 sort_flock(&mut listing);
3139 assert_eq!(
3140 listing.iter().map(|i| i.id).collect::<Vec<_>>(),
3141 vec![3, 5],
3142 "an older daemon's listing sorts exactly as it does today"
3143 );
3144 }
3145}