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}
19
20/// Daemon's handshake answer
21// wire format: changing this is a breaking change
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23pub struct HelloAck {
24 /// Daemon crate version
25 pub daemon_version: String,
26 /// Protocol version the daemon speaks
27 pub protocol: u32,
28 /// Daemon pid
29 pub pid: u32,
30}
31
32/// Serializable selector (mirror of [`crate::selector::ProcessSelector`];
33/// regex travels as its source string)
34// wire format: changing this is a breaking change
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
37pub enum SelectorSpec {
38 /// Every sheep
39 All,
40 /// By id
41 Id(u32),
42 /// By exact name
43 Name(String),
44 /// By regex source
45 Regex(String),
46 /// By fold name
47 Fold(String),
48}
49
50/// A short marker a dog attaches to a sheep for `shep flock` to paint.
51///
52/// shep stores one and prints it. It does not parse it, has no opinion about
53/// what it means, and never will: `▲ main@a1b2c3` is a deploy tool's
54/// sentence, not shep's, and keeping it that way is what makes this a general
55/// mechanism rather than one feature's field.
56///
57/// # The rule
58///
59/// A smit is non-empty once whitespace is discounted, at most
60/// [`Self::MAX_CHARS`] characters, and carries no [`char::is_control`]
61/// character — `\u{1b}` included, which `is_control` already covers and which
62/// is named separately in this doc anyway, because it is the one an attacker
63/// reaches for and a reader should not have to know the classification to see
64/// that it is handled.
65///
66/// Refused, never repaired. The text is stored exactly as it arrived: shep
67/// does not trim it, strip from it, or otherwise hand back something the
68/// publisher did not send. `crate::kv`'s key grammar and value cap set the
69/// same precedent for the same kind of value, and the publisher here is a
70/// program, so a refusal it can see and fix beats mangling it cannot.
71///
72/// # Why the cap counts characters
73///
74/// [`Self::MAX_CHARS`] is a count of `char`s, not of bytes and not of display
75/// columns. Bytes would refuse a legitimate CJK smit at roughly a third of
76/// its apparent length. Display columns are what a table renderer measures,
77/// but they depend on the terminal and on a width table this parser has no
78/// business carrying. Characters are the honest thing a validator can promise
79/// cheaply. 48 is measured against the reference smit `▲ main@a1b2c3` at
80/// thirteen: room for a long branch name, without letting one column swallow
81/// the table.
82///
83/// # Why validation lives here rather than at the renderer
84///
85/// `shep`'s own `output::width::sanitize_cell` deliberately KEEPS a
86/// well-formed CSI sequence, because shep's colouring is made of them, so it
87/// is not a guard against a third party's string. Refusing here means `shep
88/// flock`, `shep describe`, `--format json`, the lookout, the MCP tool schema
89/// and every bus subscriber are safe by construction instead of six places
90/// each remembering.
91///
92/// `Debug` is derived, and that is the deliberate decision (IR-41): a smit
93/// carries no environment and no secret. It is a string a dog asked to have
94/// painted in public, so redacting it would hide the thing an operator is
95/// debugging.
96///
97/// # Example
98/// ```
99/// use shep_core::protocol::Smit;
100///
101/// assert_eq!("▲ main@a1b2c3".parse::<Smit>()?.as_str(), "▲ main@a1b2c3");
102/// assert!("\u{1b}[2Jgone".parse::<Smit>().is_err()); // no escapes
103/// # Ok::<(), shep_core::protocol::SmitError>(())
104/// ```
105// wire format: changing this is a breaking change
106#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
107pub struct Smit(String);
108
109impl Smit {
110 /// The longest a smit may be, in characters. See the type doc for why
111 /// characters rather than bytes or display columns.
112 pub const MAX_CHARS: usize = 48;
113
114 /// The marker as text, exactly as its publisher sent it.
115 #[must_use]
116 pub fn as_str(&self) -> &str {
117 &self.0
118 }
119}
120
121impl fmt::Display for Smit {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 f.write_str(&self.0)
124 }
125}
126
127impl core::str::FromStr for Smit {
128 type Err = SmitError;
129
130 /// # Errors
131 /// - [`SmitError::Empty`] — nothing but whitespace.
132 /// - [`SmitError::TooLong`] — over [`Self::MAX_CHARS`] characters.
133 /// - [`SmitError::Unprintable`] — a control character, `\u{1b}` included.
134 fn from_str(text: &str) -> Result<Self, Self::Err> {
135 if text.trim().is_empty() {
136 return Err(SmitError::Empty);
137 }
138 let chars = text.chars().count();
139 if chars > Self::MAX_CHARS {
140 return Err(SmitError::TooLong { chars });
141 }
142 if text.chars().any(char::is_control) {
143 return Err(SmitError::Unprintable);
144 }
145 Ok(Self(text.to_string()))
146 }
147}
148
149/// Hand-written rather than derived, and that is the whole security property.
150///
151/// A derived impl would accept anything a `String` accepts, so a smit
152/// carrying `\u{1b}[2J` would reach the daemon's memory and every listing
153/// built from it. `docs/dogs.md` tells dog authors to speak this wire
154/// directly, so a dog written in another language never runs
155/// [`core::str::FromStr`] — the daemon has to validate what it decodes, not
156/// trust that it was constructed properly.
157impl<'de> Deserialize<'de> for Smit {
158 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
159 // String, not &str: a non-borrowing deserializer cannot always borrow
160 let text = String::deserialize(deserializer)?;
161 text.parse().map_err(serde::de::Error::custom)
162 }
163}
164
165/// Why a string is not a [`Smit`].
166///
167/// `#[non_exhaustive]`: shep-core is a published library and a further
168/// refusal — a grapheme-cluster cap, say, or a bidi-override rule — must not
169/// break an out-of-tree consumer's `match` (IR-20).
170#[non_exhaustive]
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum SmitError {
173 /// Over [`Smit::MAX_CHARS`] characters; carries the count that was sent.
174 TooLong {
175 /// How many characters the string held.
176 chars: usize,
177 },
178 /// A control character, `\u{1b}` included — the sequence that would let a
179 /// third party's string drive an operator's terminal.
180 Unprintable,
181 /// Empty, or nothing but whitespace.
182 Empty,
183}
184
185impl fmt::Display for SmitError {
186 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 match self {
188 Self::TooLong { chars } => write!(
189 f,
190 "a smit is at most {} characters; this one is {chars}",
191 Smit::MAX_CHARS
192 ),
193 Self::Unprintable => {
194 f.write_str("a smit may not contain a control character, an escape included")
195 }
196 Self::Empty => f.write_str("a smit may not be empty"),
197 }
198 }
199}
200
201impl core::error::Error for SmitError {}
202
203/// One RPC request (Phase 1 verb set; later phases extend)
204// wire format: changing existing variants is a breaking change
205#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
206#[serde(tag = "kind", rename_all = "snake_case")]
207#[non_exhaustive]
208pub enum Request {
209 /// Liveness check
210 Ping,
211 /// Full flock listing
212 ListFlock,
213 /// Detailed info for matching sheep
214 Describe {
215 /// Which sheep
216 selector: SelectorSpec,
217 },
218 /// Register + start apps
219 Start {
220 /// App configs — the daemon MUST re-normalize (peer input is
221 /// untrusted); failures return [`RpcErrorCode::InvalidConfig`]
222 apps: Vec<AppConfig>,
223 },
224 /// Stop matching sheep (stay registered)
225 Stop {
226 /// Which sheep
227 selector: SelectorSpec,
228 },
229 /// Restart matching sheep
230 Restart {
231 /// Which sheep
232 selector: SelectorSpec,
233 },
234 /// Replace each matching sheep with a fresh instance of the same app, one
235 /// instance of an app at a time, so the app has a window in which it can
236 /// stay reachable across the swap
237 Reload {
238 /// Which sheep. No default anywhere in the stack — a reload replaces
239 /// running processes, so the operator names the target, exactly as
240 /// `stop`/`restart`/`delete` do (see `shep reload`).
241 selector: SelectorSpec,
242 },
243 /// Stop + deregister matching sheep
244 Delete {
245 /// Which sheep
246 selector: SelectorSpec,
247 },
248 /// Set how many instances one app runs (see `shep stock`).
249 ///
250 /// # Why a name and not a selector
251 ///
252 /// Every other verb here takes a [`SelectorSpec`], and this one
253 /// deliberately does not. `instances` is a per-app number and instance
254 /// slots are allocated against the same-name group
255 /// (`shep_daemon::assemble::instance_slots`), so a selector matching two
256 /// apps would have to mean either "four of each" or "four in total", and
257 /// neither reading is more obviously right than the other. A name has one
258 /// meaning.
259 ///
260 /// # Why absolute and not a delta
261 ///
262 /// There is no `+N`/`-N` form and there will not be one. An absolute count
263 /// is idempotent — run it twice, get the same flock — where two operators
264 /// sending `+2` against the same app get a number neither of them asked
265 /// for. This project's own trace notes also record a crash on pm2's
266 /// relative-remove path, and those notes exist so shep does not reproduce
267 /// what they record.
268 Scale {
269 /// The app's name, exactly as its config spells it. Not a selector: no
270 /// `all`, no regex, no `fold:`.
271 name: String,
272 /// How many instances the app has when this returns. `0` is refused
273 /// with [`RpcErrorCode::InvalidConfig`] — `normalize` rejects
274 /// `instances == 0` for every other path into the daemon, and `shep
275 /// delete` is the verb for removing an app.
276 count: u32,
277 },
278 /// Attach a short marker to `sheep` for `shep flock` to paint, or clear
279 /// it with `None`.
280 ///
281 /// By NAME rather than a selector, for [`Self::Scale`]'s reason (see its
282 /// own doc above): a smit belongs to a sheep, not to one of its
283 /// instances, and every instance of that name shows it — including one
284 /// spawned after the smit was painted.
285 ///
286 /// Held in memory and scoped to the connection that sent it. When that
287 /// connection closes, for any reason, the smits it painted go with it. A
288 /// publisher therefore republishes rather than publishing on change.
289 ///
290 /// shep does not parse it and has no opinion about what it means.
291 SetSmit {
292 /// Which sheep.
293 sheep: String,
294 /// The marker, or `None` to clear it.
295 smit: Option<Smit>,
296 },
297 /// Reopen every matched sheep's log files, for an external rotator that
298 /// has renamed them (`create`-mode rotation)
299 Reopen {
300 /// Which sheep
301 selector: SelectorSpec,
302 },
303 /// Empty every matched sheep's log files: flush what is still pending,
304 /// then truncate the recorded paths
305 Flush {
306 /// Which sheep. No default anywhere in the stack — this destroys
307 /// log data, so the operator names the target (see `shep flush`).
308 selector: SelectorSpec,
309 },
310 /// Send a named action to every matched sheep over its shepherd channel
311 /// and report what each app says back (see `shep trigger`).
312 Trigger {
313 /// Which sheep. No default anywhere in the stack, matching
314 /// `stop`/`restart`/`reload`/`delete`/`flush`: an operator names the
315 /// target rather than trigger an action against the whole flock by
316 /// accident.
317 selector: SelectorSpec,
318 /// The action name. Free-form — the daemon never declares, parses,
319 /// or validates it; an app that does not recognize the name is
320 /// expected to say so in its own reply rather than stay silent.
321 action: String,
322 /// Argument text for the action, passed through to the app
323 /// verbatim. One opaque string, not structured data: the daemon
324 /// holds no schema for it, matching the shepherd channel's own
325 /// `action` message this ultimately becomes.
326 params: Option<String>,
327 },
328 /// Deliver one signal to every matched sheep's OWN process — never its
329 /// process group (see `shep signal`).
330 Signal {
331 /// Which sheep. No default anywhere in the stack, matching every
332 /// other verb that reaches a running process: an operator names the
333 /// target rather than signal the whole flock by accident.
334 selector: SelectorSpec,
335 /// The signal's name, as
336 /// [`OperatorSignal`](crate::signals::OperatorSignal) spells it — the
337 /// `SIG` prefix and the case are both optional.
338 ///
339 /// A `String` rather than the enum, for the reason
340 /// [`AppConfig::kill_signal`](crate::config::AppConfig::kill_signal)
341 /// is one: the wire stays plain text a person can read in a capture,
342 /// and the daemon re-validates regardless, because peer input is
343 /// untrusted. A name outside the grammar answers
344 /// [`RpcErrorCode::InvalidConfig`].
345 signal: String,
346 },
347 /// Write one line to every matched sheep's stdin (see `shep whisper`).
348 SendLine {
349 /// Which sheep. No default, matching every other verb that reaches a
350 /// running process.
351 selector: SelectorSpec,
352 /// The line, WITHOUT its terminator — the shepherd appends exactly one
353 /// `\n` when it writes. Carrying the terminator here would leave "did
354 /// the caller include one" as a question every hop has to re-answer,
355 /// and a caller that included two would send an empty line the app
356 /// never asked for.
357 ///
358 /// A line containing an embedded newline is refused
359 /// ([`RpcErrorCode::InvalidConfig`]): it would deliver two commands
360 /// where the operator typed one.
361 line: String,
362 },
363 /// Write the muster roll now, bypassing the snapshot writer's debounce
364 SaveRoll,
365 /// Assemble the flock from the muster roll on disk: start every app the
366 /// roll recorded running, leaving every app the flock already has exactly
367 /// as it stands
368 Muster,
369 /// Ask for one dog's `[dog.<name>]` section, as the dog itself parses it
370 DogConfig {
371 /// The dog's name — the config key, not a selector
372 name: String,
373 },
374 /// Start one dog now, marking it as coming from `source`
375 EnableDog {
376 /// The dog's name
377 name: String,
378 /// Where its binary comes from
379 source: DogSource,
380 },
381 /// Stop and deregister one dog
382 ///
383 /// Answers [`Response::Deleted`], the same reply `Delete` gives: disabling
384 /// deregisters exactly as `Delete` does, so this is the same fact and not
385 /// a coincidence of shape. A variant of its own (`DogDisabled`, say) would
386 /// carry nothing `Deleted` does not.
387 DisableDog {
388 /// The dog's name
389 name: String,
390 },
391 /// Graceful daemon shutdown
392 KillDaemon,
393 /// Subscribe this connection to bus topics (glob patterns)
394 Subscribe {
395 /// Topic globs, e.g. `process.*`
396 topics: Vec<String>,
397 },
398}
399
400/// Where a dog came from: this binary, or one an operator adopted.
401///
402/// The one thing an operator wants when a dog misbehaves, which is why it
403/// is a column rather than a detail. Carried on [`ProcessInfo::dog`], so a
404/// listing distinguishes the two populations without a second request.
405///
406/// `#[non_exhaustive]`: a future source — a dog fetched from a registry,
407/// say — must not need a protocol version bump (IR-20).
408// wire format: changing existing variants is a breaking change
409#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
410#[serde(tag = "kind", rename_all = "snake_case")]
411#[non_exhaustive]
412pub enum DogSource {
413 /// An argv branch of the shep binary itself (`shep dog <name>`).
414 BuiltIn,
415 /// A binary an operator adopted, run at the daemon's own trust level.
416 Adopted {
417 /// The binary's path, exactly as the operator gave it to `adopt`.
418 path: String,
419 },
420}
421
422/// One process the OS reports as a descendant of a sheep.
423///
424/// # What this is not
425///
426/// It is **not** the set of processes that die with the sheep, and nothing here
427/// should be read as promising that. The list is built by walking the OS's
428/// parent-pid links; the stop ladder acts on the process GROUP, and the two
429/// units diverge in both directions — a lamb that forks and exits leaves its
430/// own children re-parented to init, out of this list and still in the group,
431/// while a `setsid()` grandchild stays in this list and leaves the group.
432/// shep-daemon's `limits` module doc has the full account, and it is the
433/// authority; this is a pointer to it, not a second copy free to drift.
434///
435/// # Why a name and not a command line
436///
437/// `name` is the executable's name as the OS reports it (`node`, `sh`,
438/// `python3`), never its argument vector. A process's argv routinely carries
439/// credentials — a `--password=` flag, a URL with a token in the query string —
440/// and this field rides in `shep describe --format json`, which is output
441/// people paste into bug reports. A pid alone would be safe too, and was
442/// considered; it was rejected because a tree of bare integers sends the
443/// operator to `ps`, which is the work the tree exists to save.
444///
445/// # Why no memory figure
446///
447/// The sheep's own row already reports its whole tree's resident size
448/// ([`ProcessInfo::memory_bytes`]), and a per-lamb breakdown is a profiler's
449/// job. `deferred.md`'s note on this struct's growth asks for exactly this
450/// restraint.
451///
452/// `#[non_exhaustive]`: shep-core is a published library, this type is new, and
453/// the two obvious next fields (a parent pid, so a deep tree can be nested
454/// rather than flattened; a start time) would otherwise be breaking additions
455/// (IR-20). Build one with [`Self::new`].
456// wire format: changing this is a breaking change
457#[non_exhaustive]
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
459pub struct Lamb {
460 /// The lamb's own pid.
461 pub pid: u32,
462 /// The executable's name, as the OS reports it. Never its command line.
463 pub name: String,
464}
465
466impl Lamb {
467 /// One lamb.
468 ///
469 /// A plain constructor rather than a builder, unlike [`ProcessInfo`]: both
470 /// fields are required and neither is optional or derived, which is the
471 /// case a builder buys nothing for.
472 #[must_use]
473 pub fn new(pid: u32, name: impl Into<String>) -> Self {
474 Self {
475 pid,
476 name: name.into(),
477 }
478 }
479}
480
481/// Why a sheep's process most recently stopped existing under this daemon.
482///
483/// Not shep-daemon's own `ExitOutcome` reused directly: that type lives
484/// behind the spawn-runner seam (`ProcessRunner::wait`, in shep-daemon's
485/// `runner` module) and is free to grow with whatever the real runner needs
486/// to observe next without dragging a breaking wire change behind it — this
487/// one only ever grows on its own say-so. The two happen to carry the same
488/// two fields today because the runner's own observation IS the honest exit
489/// outcome; shep-daemon converts one into the other at the point it records
490/// it (`Actor::handle_exited`), rather than this crate depending on
491/// shep-daemon's internals to reuse its type.
492///
493/// A struct, not two flat `Option<i32>` fields on [`ProcessInfo`] directly:
494/// with two flat fields, "this sheep has never exited under this daemon"
495/// and "it exited, killed by a signal this daemon did not name" are both
496/// all-`None`, and a reader cannot tell those apart. Nested behind
497/// [`ProcessInfo::last_exit`]'s own `Option`, that ambiguity moves up a
498/// level where it belongs: `None` there means "never exited"; `Some` means
499/// "exited, and here is what this daemon knows about it" — which itself
500/// mirrors the OS's own exited-normally/killed-by-signal split
501/// (`WIFEXITED`/`WIFSIGNALED`): ordinarily exactly one of `code`/`signal` is
502/// `Some`. A reader must not assume both can never be `None` together,
503/// though — that would still mean "this daemon recorded an exit; it could
504/// not characterize how" rather than "this sheep never exited", and this
505/// type does not forbid it.
506///
507/// No `#[non_exhaustive]`, unlike every other struct on this wire: those
508/// grow because a discriminator does (`ProcessInfo`'s own doc lists its
509/// four so far); `code`/`signal` is already the complete
510/// exited-normally/killed-by-signal split the runner exposes, this crate
511/// has no libc to derive a richer wait-status decomposition from even if it
512/// wanted one, and there is no forecast next field. Adding the attribute
513/// back later is a compatible change the day a real need appears (IR-16
514/// style); carrying it now on nothing but "might grow" is the exact
515/// speculative case IR-20 warns against.
516// wire format: changing this is a breaking change
517#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
518pub struct ExitInfo {
519 /// The process's own exit code, set on a normal exit (`WIFEXITED`).
520 pub code: Option<i32>,
521 /// The raw unix signal number that ended the process, set when it did
522 /// not exit on its own (`WIFSIGNALED`) — an operator's own `shep stop`
523 /// or `shep delete` included: the process still genuinely stopped by a
524 /// signal, and that stays true information even though shep, not a
525 /// crash, is what asked for it. Raw and platform-specific for the same
526 /// reason [`crate::signals::OperatorSignal`] carries no such accessor —
527 /// see that type's own module doc — so rendering this as a name
528 /// (`SIGKILL` rather than `9`) is a job for whichever OS-aware layer
529 /// reads it, never for this crate.
530 pub signal: Option<i32>,
531}
532
533/// Snapshot of one sheep for listings and events
534// wire format: changing this is a breaking change
535//
536// `out_file`/`err_file` are `Option<String>`, and both halves of that are
537// deliberate:
538//
539// String, not PathBuf. Every path already on this wire travels as a string
540// (`AppConfig::script`, `cwd`, `out_file`, `err_file`, all of which ride in
541// `Request::Start`), so this matches the established representation. It is
542// also the safer failure mode: serde's `PathBuf` impl REFUSES a non-UTF-8
543// path, and that refusal is not local — it aborts the whole `Reply`, so one
544// sheep with an odd log path would blank the entire `ListFlock` for every
545// other sheep. Lossy conversion daemon-side degrades exactly one field of
546// one sheep instead.
547//
548// Option, not a bare String. Semantically the daemon always resolves both
549// paths, so a required field is tempting. But the handshake only compares
550// `PROTOCOL_VERSION` (see shep-daemon's `server.rs`), and adding these
551// fields deliberately does NOT bump it — the evolution rule in this
552// module's parent says additive fields keep the version. A daemon built
553// before this field and a client built after it therefore both announce
554// protocol 1 and connect happily, and that daemon's replies carry no
555// `out_file` key at all. A required `String` would fail to deserialize
556// there, so a new client could not list against an old daemon. `None`
557// means precisely "this peer predates the field" — which readers must
558// render as unknown, NOT as "this sheep has no log file".
559//
560// `cpu_percent`/`memory_bytes` are optional for that same skew reason and
561// for one of their own: a sheep that is not running has no resource use to
562// report, and one that has been up for less than a sampling window has no
563// honest CPU figure. All three cases render as unknown, never as zero.
564//
565// No `Eq`, which every other wire struct in this module derives:
566// `cpu_percent` is an `f32` and floats are only partially ordered. Nothing
567// compares a `ProcessInfo` for total equality — `assert_eq!` needs only
568// `PartialEq`, and no listing is keyed on, hashed by, or sorted by a whole
569// row.
570/// `#[non_exhaustive]`: this struct has now grown a field in five separate
571/// phases (`out_file`/`err_file`, then `cpu_percent`/`memory_bytes`, then
572/// `dog`, then `lambs`, then `last_exit`) with no hand-edit sweep across the
573/// workspace for any of them — the attribute is paying for itself exactly
574/// as advertised. Corrected from an earlier version of this comment, which
575/// overstated `deferred.md`'s own `ProcessInfo` entry as a warning against
576/// growing this struct at all: what that entry actually defers is
577/// SPLITTING it into several smaller types, and calls this attribute plus
578/// [`ProcessInfo::builder`] "deliberately the opposite of forcing the split
579/// early" — i.e. exactly what makes a field like `last_exit` cheap to add
580/// for a concrete operator need, not a reason to withhold one. Use
581/// [`ProcessInfo::builder`] to construct one; the fields stay `pub`, so
582/// reading them and assigning to them are both unchanged.
583#[non_exhaustive]
584#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
585pub struct ProcessInfo {
586 /// Stable numeric id
587 pub id: u32,
588 /// Sheep name
589 pub name: String,
590 /// Lifecycle status
591 pub status: ProcStatus,
592 /// OS pid while running
593 pub pid: Option<u32>,
594 /// Restart count since registration
595 pub restarts: u32,
596 /// Milliseconds since last successful start
597 pub uptime_ms: u64,
598 /// Fold membership
599 pub fold: Option<String>,
600 /// Resolved stdout log path: the app's explicit
601 /// [`AppConfig::out_file`] when it set one, else the daemon-derived
602 /// default. `None` only when the peer daemon predates this field.
603 pub out_file: Option<String>,
604 /// Resolved stderr log path, resolved exactly as [`Self::out_file`]
605 pub err_file: Option<String>,
606 /// Tree CPU as a percentage of one core, over the window since the
607 /// daemon's last periodic sample. `None` when the sheep is not running,
608 /// when it has been up for less than one sampling window, or when the
609 /// peer daemon predates this field — all three of which a reader
610 /// renders as unknown, never as zero.
611 ///
612 /// A value over 100 is a tree using more than one core, not a bug.
613 pub cpu_percent: Option<f32>,
614 /// Tree resident set size in bytes, current as of the reply. `None`
615 /// under the same three conditions as [`Self::cpu_percent`], minus the
616 /// window one — memory needs no baseline.
617 pub memory_bytes: Option<u64>,
618 /// Set when this entry is a dog, naming where the dog came from;
619 /// `None` for a sheep.
620 ///
621 /// Unlike [`Self::cpu_percent`], `None` here does not need to enumerate
622 /// three cases. A daemon built before dogs existed has none, so "not a
623 /// dog" is the true answer whether this peer predates the field or the
624 /// entry is genuinely a sheep — there is no resource-usage-style claim
625 /// a stale zero could get wrong. Do not "fix" this into three cases.
626 pub dog: Option<DogSource>,
627 /// The processes the OS reports as descendants of this sheep, or `None`
628 /// when this reply did not walk for them.
629 ///
630 /// `None` covers two cases and is deliberately not a third: this reply is
631 /// not a `Describe` (only `Describe` walks — the walk costs a second pass
632 /// over the machine's process table, and a flock listing is the thing an
633 /// operator leaves running in a loop), or the peer daemon predates the
634 /// field. `Some(vec![])` is the third case, and the one that means what it
635 /// looks like: walked, and this sheep has no children.
636 ///
637 /// Read [`Lamb`]'s own doc before rendering this. The list is a parent-pid
638 /// walk and is NOT the set of processes a stop kills; any output built from
639 /// it has to say so where the operator will see it.
640 pub lambs: Option<Vec<Lamb>>,
641 /// How this sheep's process most recently stopped existing under this
642 /// daemon. `None` while it has never exited under this daemon — either
643 /// it has not been started yet, or it is still on its very first run —
644 /// and also when the peer daemon predates this field, the same skew
645 /// rule [`Self::out_file`] documents for itself.
646 ///
647 /// Sticky across a respawn, deliberately: this is the daemon's answer
648 /// to "why did it last stop", not "is it stopped right now" — `status`
649 /// and `pid` already answer that, and a sheep back `Online` after a
650 /// crash still has a true story to tell about the crash that restarted
651 /// it. It updates only on the next exit, never cleared by one starting
652 /// back up.
653 pub last_exit: Option<ExitInfo>,
654 /// The marker a dog has asked to have painted beside this sheep, or
655 /// `None` when no dog has painted one — which also covers a peer daemon
656 /// that predates the field, the same skew rule [`Self::out_file`]
657 /// documents for itself.
658 ///
659 /// A `String` rather than a [`Smit`], deliberately: a client decoding a
660 /// listing from a daemon that already validated the text should not have
661 /// to re-run the parser, and [`ProcessInfo`] is a report rather than an
662 /// input. The validation that makes this safe to print happened at the
663 /// daemon's ingress — see [`Smit`] for why there and not at the renderer.
664 ///
665 /// Every instance of a name shows the same marker: smits are keyed by
666 /// sheep name, not by instance id.
667 pub smit: Option<String>,
668}
669
670impl ProcessInfo {
671 /// Starts a builder for one sheep's row.
672 ///
673 /// The three required arguments are the three fields no row can omit and
674 /// no reader can default: which sheep this is, what it is called, and
675 /// what state it is in. Everything else is optional, derived, or
676 /// meaningfully absent, which is exactly the shape a builder is for —
677 /// a nine-argument `new` would put `Option<String>, Option<String>,
678 /// Option<f32>, Option<u64>` next to each other at every call site and
679 /// invite a silent transposition the type system could not catch.
680 ///
681 /// No `#[must_use]` here: [`ProcessInfoBuilder`] already carries one,
682 /// which clippy's `double_must_use` lint treats as covering this
683 /// function's return too.
684 pub fn builder(id: u32, name: impl Into<String>, status: ProcStatus) -> ProcessInfoBuilder {
685 ProcessInfoBuilder {
686 info: Self {
687 id,
688 name: name.into(),
689 status,
690 pid: None,
691 restarts: 0,
692 uptime_ms: 0,
693 fold: None,
694 out_file: None,
695 err_file: None,
696 cpu_percent: None,
697 memory_bytes: None,
698 dog: None,
699 lambs: None,
700 last_exit: None,
701 smit: None,
702 },
703 }
704 }
705}
706
707/// Builds a [`ProcessInfo`], which is `#[non_exhaustive]` and so cannot be
708/// written as a struct literal outside this crate.
709///
710/// Every setter takes the field's own type, `Option` included, rather than
711/// the unwrapped value. That is deliberate and it is the difference between a
712/// straight port and a rewrite: the daemon already holds `Option<u32>` for a
713/// pid and `Option<f32>` for a CPU reading, so `.pid(entry.pid())` carries
714/// across unchanged where `.pid(u32)` would put an `if let` ladder at every
715/// call site. A setter is skipped, not passed `None`, when a row genuinely
716/// has nothing to say about that field.
717///
718/// Defaults for the skipped fields are the ones a not-yet-running sheep has:
719/// no pid, no uptime, no restarts, no resource reading, not a dog, never
720/// exited.
721#[derive(Debug, Clone)]
722#[must_use = "a builder that is never `build`-ed produces no ProcessInfo"]
723pub struct ProcessInfoBuilder {
724 info: ProcessInfo,
725}
726
727impl ProcessInfoBuilder {
728 /// Sets the OS pid; `None` while the sheep is not running.
729 pub fn pid(mut self, pid: Option<u32>) -> Self {
730 self.info.pid = pid;
731 self
732 }
733
734 /// Sets the restart count since registration.
735 pub fn restarts(mut self, restarts: u32) -> Self {
736 self.info.restarts = restarts;
737 self
738 }
739
740 /// Sets milliseconds since the last successful start.
741 pub fn uptime_ms(mut self, uptime_ms: u64) -> Self {
742 self.info.uptime_ms = uptime_ms;
743 self
744 }
745
746 /// Sets fold membership.
747 pub fn fold(mut self, fold: Option<String>) -> Self {
748 self.info.fold = fold;
749 self
750 }
751
752 /// Sets the resolved stdout log path.
753 pub fn out_file(mut self, out_file: Option<String>) -> Self {
754 self.info.out_file = out_file;
755 self
756 }
757
758 /// Sets the resolved stderr log path.
759 pub fn err_file(mut self, err_file: Option<String>) -> Self {
760 self.info.err_file = err_file;
761 self
762 }
763
764 /// Sets tree CPU as a percentage of one core.
765 pub fn cpu_percent(mut self, cpu_percent: Option<f32>) -> Self {
766 self.info.cpu_percent = cpu_percent;
767 self
768 }
769
770 /// Sets tree resident set size in bytes.
771 pub fn memory_bytes(mut self, memory_bytes: Option<u64>) -> Self {
772 self.info.memory_bytes = memory_bytes;
773 self
774 }
775
776 /// Marks this row a dog and names where the dog came from.
777 pub fn dog(mut self, dog: Option<DogSource>) -> Self {
778 self.info.dog = dog;
779 self
780 }
781
782 /// Sets the sheep's lamb list; `None` when this reply did not walk for one.
783 pub fn lambs(mut self, lambs: Option<Vec<Lamb>>) -> Self {
784 self.info.lambs = lambs;
785 self
786 }
787
788 /// Sets how this sheep's process most recently stopped; `None` while it
789 /// has never exited under this daemon.
790 pub fn last_exit(mut self, last_exit: Option<ExitInfo>) -> Self {
791 self.info.last_exit = last_exit;
792 self
793 }
794
795 /// Sets the marker a dog has painted on this sheep; `None` when none has.
796 pub fn smit(mut self, smit: Option<String>) -> Self {
797 self.info.smit = smit;
798 self
799 }
800
801 /// Finishes the row.
802 #[must_use]
803 pub fn build(self) -> ProcessInfo {
804 self.info
805 }
806}
807
808/// What happened when the daemon tried to deliver one sheep's triggered
809/// action.
810///
811/// `#[non_exhaustive]`: a future outcome — distinguishing a malformed reply
812/// from a well-formed one, say, or a second trigger already in flight for
813/// the same sheep — must not need a protocol version bump (IR-20).
814// wire format: changing existing variants is a breaking change
815#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
816#[serde(tag = "kind", rename_all = "snake_case")]
817#[non_exhaustive]
818pub enum ActionOutcome {
819 /// The app answered on the shepherd channel.
820 Replied {
821 /// The reply body, exactly as the app sent it.
822 body: String,
823 },
824 /// The sheep had no reachable shepherd channel for the daemon to
825 /// deliver the action over.
826 NoChannel,
827 /// The sheep is a reload drainee — mid-swap, on its way out — and the
828 /// daemon skipped it rather than deliver the action to a process
829 /// already being replaced.
830 Skipped,
831 /// The daemon delivered the action, but no reply arrived before the
832 /// app's configured action timeout elapsed.
833 TimedOut,
834}
835
836/// One matched sheep's row in a `Trigger` reply.
837///
838/// `EmptiedFile` (`crates/shep-cli/src/output/rows.rs`) is the precedent for
839/// a non-`ProcessInfo` row: a reply body has nowhere to live on
840/// [`ProcessInfo`], and [`Self::outcome`] is per-row rather than a
841/// whole-request refusal because spec §9's selector grammar (`all`,
842/// `/regex/`, `fold:`) makes a mixed flock the normal case — the same reason
843/// `Reopen`/`Flush` report per-item failure inside a success rather than
844/// failing the whole request.
845// wire format: changing this is a breaking change
846#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
847pub struct ActionReply {
848 /// The sheep's stable id.
849 pub id: u32,
850 /// The sheep's name.
851 pub name: String,
852 /// What happened when the daemon tried to deliver the action.
853 pub outcome: ActionOutcome,
854}
855
856/// What happened when the shepherd tried to deliver one signal.
857///
858/// `#[non_exhaustive]`: a future outcome — a sheep refused because it is a dog,
859/// say, or a delivery held while a stop ladder runs — must not need a protocol
860/// version bump (IR-20).
861// wire format: changing existing variants is a breaking change
862#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
863#[serde(tag = "kind", rename_all = "snake_case")]
864#[non_exhaustive]
865pub enum SignalOutcome {
866 /// The kernel accepted the signal for this sheep's pid.
867 ///
868 /// Says the signal was delivered, not that the app did anything with it.
869 /// A signal the app blocks, ignores, or has no handler for is `Delivered`
870 /// exactly like one it acts on — there is nothing on this path that could
871 /// tell the difference, and pretending otherwise would be the dishonest
872 /// half of an honest report.
873 Delivered,
874 /// The sheep is registered but has no live process to signal — stopped,
875 /// errored, or waiting out a restart backoff.
876 NotRunning,
877 /// The kernel refused the delivery; carries its reason (`ESRCH` for a
878 /// process reaped between the lookup and the syscall, `EPERM` for one this
879 /// daemon may not signal).
880 Failed {
881 /// The refusal, as the OS worded it.
882 reason: String,
883 },
884}
885
886/// One matched sheep's row in a `Signal` reply.
887///
888/// Shaped exactly like [`ActionReply`] and for the same reason: spec §9's
889/// selector grammar (`all`, `/regex/`, `fold:`) makes a mixed flock the normal
890/// case, so a per-row outcome beats a whole-request refusal that would leave
891/// the operator unable to tell which half was taken.
892// wire format: changing this is a breaking change
893#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
894pub struct SignalReply {
895 /// The sheep's stable id.
896 pub id: u32,
897 /// The sheep's name.
898 pub name: String,
899 /// What happened when the shepherd tried to deliver the signal.
900 pub outcome: SignalOutcome,
901}
902
903/// What happened when the shepherd tried to write one line to a sheep's stdin.
904///
905/// `#[non_exhaustive]`: a future outcome — a sheep refused because its pipe is
906/// backed up, say — must not need a protocol version bump (IR-20).
907// wire format: changing existing variants is a breaking change
908#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
909#[serde(tag = "kind", rename_all = "snake_case")]
910#[non_exhaustive]
911pub enum LineOutcome {
912 /// The line was written to the pipe and flushed.
913 ///
914 /// Says the bytes left the shepherd, not that the app read them. A pipe
915 /// holds 64 KiB before it blocks, so a short line to an app that never
916 /// reads its stdin is `Sent` — which is honest, because there is nothing
917 /// on this path that could tell the difference and a supervisor inventing
918 /// one would be guessing.
919 Sent,
920 /// The sheep has no stdin pipe: its config does not set `stdin = true`, or
921 /// it is not running.
922 ///
923 /// One outcome for two causes, deliberately. The row is read to answer
924 /// "why did my line not arrive", and both answers are "there is no pipe
925 /// here"; splitting them would put the operator in front of a distinction
926 /// with the same fix behind it. A sheep that is not running is visible as
927 /// such in `shep flock`, which is where that question belongs.
928 NoStdin,
929 /// The shepherd had a pipe and did not confirm a write to it; carries
930 /// why.
931 ///
932 /// Three shapes reach it: the write failed (the far end is gone —
933 /// normally the app exiting between the lookup and the write), the line
934 /// arrived to find the sheep's queue already full, or the write did not
935 /// finish inside the shepherd's own bound. The reason names which,
936 /// because the operator's next move differs.
937 ///
938 /// # The last shape does not promise the line was never written
939 ///
940 /// "Did not confirm", not "could not write", and the difference is the
941 /// operator's whole decision about retrying. A write that timed out is a
942 /// write the shepherd stopped WAITING for: the bytes may be part-written
943 /// into a pipe the app is not draining, and they land in full the moment
944 /// it does. There is no way to take them back — abandoning a write
945 /// halfway would leave a partial line in the pipe, which is worse than a
946 /// slow one.
947 ///
948 /// What the shepherd does do is drop a line still QUEUED behind that one
949 /// once its caller has given up, so retrying a `sendline` cannot pile
950 /// duplicates up behind a wedged pipe and deliver them together later.
951 /// The first line of a retry sequence is the one that can still arrive
952 /// late; treat a retry as a second command, not a repeat of the first.
953 NotWritten {
954 /// What went wrong, in plain English.
955 reason: String,
956 },
957}
958
959/// One matched sheep's row in a `SendLine` reply.
960///
961/// Same shape and same argument as [`ActionReply`] and [`SignalReply`]: spec
962/// §9's selector grammar makes a mixed flock the normal case, so an outcome
963/// per row beats a whole-request refusal.
964// wire format: changing this is a breaking change
965#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
966pub struct LineReply {
967 /// The sheep's stable id.
968 pub id: u32,
969 /// The sheep's name.
970 pub name: String,
971 /// What happened.
972 pub outcome: LineOutcome,
973}
974
975/// A dog's `[dog.<name>]` config section, carried as TOML text.
976///
977/// This travels over the socket rather than the child's environment for
978/// exactly one reason: a dog's section routinely holds webhook credentials
979/// (a Discord or Slack URL with a bearer token embedded), and the socket
980/// path keeps that out of the process table and out of crash dumps. A
981/// derived `Debug` on [`Response`] would undo that the moment something
982/// logs a reply — see the manual `Debug` below, which prints only a length.
983///
984/// `#[serde(transparent)]` makes the wire representation identical to a
985/// bare `String`: this newtype changes nothing about
986/// [`crate::protocol::PROTOCOL_VERSION`] or the pinned snapshot fixtures.
987#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
988#[serde(transparent)]
989pub struct DogSectionToml(String);
990
991impl DogSectionToml {
992 /// The TOML text, empty when the file has no such section.
993 #[must_use]
994 pub fn as_str(&self) -> &str {
995 &self.0
996 }
997}
998
999impl From<String> for DogSectionToml {
1000 fn from(toml: String) -> Self {
1001 Self(toml)
1002 }
1003}
1004
1005impl core::ops::Deref for DogSectionToml {
1006 type Target = str;
1007
1008 fn deref(&self) -> &str {
1009 &self.0
1010 }
1011}
1012
1013/// Debug does not print the section body (IR-41) — see the type doc for why.
1014/// Exact-string-tested below (`dog_section_toml_debug_does_not_leak`) so a
1015/// future `#[derive(Debug)]` fails that test instead of silently reopening
1016/// the leak.
1017impl fmt::Debug for DogSectionToml {
1018 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1019 write!(f, "DogSectionToml(<{} bytes>)", self.0.len())
1020 }
1021}
1022
1023/// One RPC response (pairs with [`Request`] variants)
1024///
1025/// Ten variants carry a bare `Vec<ProcessInfo>` (`Flock`, `Described`,
1026/// `Started`, `Stopped`, `Restarted`, `Reloading`, `Scaled`, `Reopened`,
1027/// `Flushed`, `Mustered`), and that repetition is intentional — do not
1028/// collapse them into one. Each names which request it answers, which is what
1029/// lets a variant diverge later without a protocol bump: `Reloading` already
1030/// means an acceptance rather than a result, `Scaled` already means only the
1031/// survivors on a scale-down rather than every matched row, and `Mustered`
1032/// already means "every sheep of every restored app" rather than "what this
1033/// call started". A single `Listing(Vec<ProcessInfo>)` would have to
1034/// relitigate all three as a breaking change.
1035// wire format: changing existing variants is a breaking change
1036//
1037// `large_enum_variant` allowed, not fixed: `DogStarted` holds a whole
1038// `ProcessInfo` inline where every other variant holds a `Vec` of them, and
1039// adding `smit` to that struct is what pushed the spread past the lint's
1040// threshold. Clippy's remedy is to box the payload, which would be a source
1041// break for every `Response::DogStarted(info)` in and out of this workspace
1042// — for nothing: a `Response` is built once per reply and serialized
1043// immediately, so the size it occupies on one stack frame in between is not
1044// a cost anybody pays. The wire shape is identical either way.
1045#[allow(clippy::large_enum_variant)]
1046#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1047#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
1048#[non_exhaustive]
1049pub enum Response {
1050 /// Answer to `Ping`
1051 Pong,
1052 /// Answer to `ListFlock`
1053 Flock(Vec<ProcessInfo>),
1054 /// Answer to `Describe`
1055 Described(Vec<ProcessInfo>),
1056 /// Answer to `Start`
1057 Started(Vec<ProcessInfo>),
1058 /// Answer to `Stop`
1059 Stopped(Vec<ProcessInfo>),
1060 /// Answer to `Restart`
1061 Restarted(Vec<ProcessInfo>),
1062 /// Answer to `Reload` — an ACCEPTANCE, not a result, and the only reply
1063 /// in this enum carrying a flock listing that names one rather than
1064 /// finished work. [`Self::ShuttingDown`] is an acceptance too, sent
1065 /// before the daemon actually goes down, but it carries nothing.
1066 ///
1067 /// One instance costs a readiness wait plus a drain in the worst case, so
1068 /// a clustered app outlasts any deadline a client is allowed to ask for.
1069 /// The daemon therefore answers as soon as the reload is accepted, with
1070 /// the matched sheep as they stood at that moment, and the swaps report
1071 /// themselves on the bus — `process.reload`, `process.reloaded`,
1072 /// `process.reload_abandoned`. A matched sheep with nothing to replace is
1073 /// listed here as the no-op success it is, so this carries the same
1074 /// matches `Describe` would.
1075 Reloading(Vec<ProcessInfo>),
1076 /// Answer to `Scale` — the app's instances that will REMAIN, one row each,
1077 /// in instance-slot order.
1078 ///
1079 /// Scaling up, these are the instances that exist, the new ones included,
1080 /// and the answer is complete.
1081 ///
1082 /// Scaling down, these are the survivors and the departing instances are
1083 /// deliberately absent, even though they are still running their kill
1084 /// ladders as this reply is written. The operator asked for a number; this
1085 /// is that number of rows. Listing the departing ones as well would answer
1086 /// a `scale web 2` with four rows, which is the one thing the reply must
1087 /// not do. The departures report themselves on the bus as `process.delete`
1088 /// — the same split `Reloading` already makes between an acceptance and
1089 /// the swaps that follow it.
1090 Scaled(Vec<ProcessInfo>),
1091 /// Answer to `SetSmit` — every instance of the named sheep, one row
1092 /// each, each carrying the smit as it now stands.
1093 ///
1094 /// Its own variant rather than one of the ten above, on this enum's own
1095 /// stated terms: each of them names which request it answers so that one
1096 /// can diverge later without a protocol bump. A future `SetSmit` reply
1097 /// that also reported which connection holds the mark would have nowhere
1098 /// to go if this shared `Scaled`.
1099 SmitPainted(Vec<ProcessInfo>),
1100 /// Answer to `Delete` — ids removed
1101 Deleted(Vec<u32>),
1102 /// Answer to `Reopen` — every matched sheep, running or not. A sheep with
1103 /// no live log pump has nothing to reopen and is reported as a success,
1104 /// so this carries the same matches `Describe` would.
1105 Reopened(Vec<ProcessInfo>),
1106 /// Answer to `Flush` — one row per matched sheep, running or not, exactly
1107 /// as [`Self::Reopened`].
1108 ///
1109 /// One row per SHEEP, not per file emptied. Several sheep can share one
1110 /// log path (`merge_logs`, or an explicit `out_file` on a multi-instance
1111 /// app), and the daemon truncates each distinct path once — but the
1112 /// selector names sheep, so the answer names sheep, and the count here
1113 /// matches what `Describe` would return for the same selector.
1114 Flushed(Vec<ProcessInfo>),
1115 /// Answer to `Trigger` — one [`ActionReply`] row per matched sheep,
1116 /// carrying what each one answered rather than a flock listing:
1117 /// `ProcessInfo` has nowhere to hold a reply body.
1118 Triggered(Vec<ActionReply>),
1119 /// Answer to `Signal` — one [`SignalReply`] row per matched sheep.
1120 ///
1121 /// Not a flock listing: what a caller wants back is per-instance delivery,
1122 /// and [`ProcessInfo`] has nowhere to hold it. Same reasoning, and the
1123 /// same row-shaped answer, as [`Self::Triggered`].
1124 Signalled(Vec<SignalReply>),
1125 /// Answer to `SendLine` — one [`LineReply`] row per matched sheep.
1126 SentLine(Vec<LineReply>),
1127 /// Answer to `SaveRoll`
1128 RollSaved {
1129 /// Absolute path of the roll the daemon wrote
1130 path: String,
1131 /// How many apps that roll records
1132 apps: u32,
1133 },
1134 /// Answer to `Muster` — every sheep of every app the roll restored, not
1135 /// only the ones this call spawned.
1136 ///
1137 /// The distinction is the whole point of the reply. Assembling a flock
1138 /// that is already assembled starts nothing, so a listing of what this
1139 /// call spawned would be empty there — indistinguishable from an empty
1140 /// roll, which is the one outcome an operator needs to tell apart.
1141 Mustered(Vec<ProcessInfo>),
1142 /// Answer to `DogConfig` — the dog's own section, rendered back to TOML.
1143 ///
1144 /// `toml` is [`DogSectionToml`], not a bare `String`: this text
1145 /// routinely carries webhook credentials, and the newtype's manual
1146 /// `Debug` keeps them out of a `{:?}`-formatted `Response` — see that
1147 /// type's docs for why the section travels over the socket at all.
1148 DogSection {
1149 /// The `[dog.<name>]` table as TOML text, empty when the file has
1150 /// no such section
1151 toml: DogSectionToml,
1152 },
1153 /// Answer to `EnableDog` — the dog as it stands now
1154 DogStarted(ProcessInfo),
1155 /// Answer to `Subscribe`
1156 Subscribed,
1157 /// Answer to `KillDaemon`
1158 ShuttingDown,
1159}
1160
1161/// A request frame
1162// wire format: changing this is a breaking change
1163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1164pub struct Envelope {
1165 /// Per-connection request id
1166 pub id: u64,
1167 /// Client-imposed deadline (daemon aborts work past it)
1168 pub deadline_ms: Option<u64>,
1169 /// The request
1170 pub body: Request,
1171}
1172
1173/// A reply frame
1174///
1175/// `result` uses serde's stock `Result` representation — the wire carries
1176/// `{"Ok": ...}` / `{"Err": ...}` (capitalized keys). Deliberate, pinned by
1177/// snapshot: stock serde beats a custom enum the client would convert anyway.
1178// wire format: changing this is a breaking change
1179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1180pub struct Reply {
1181 /// Echoes [`Envelope::id`]
1182 pub id: u64,
1183 /// The outcome
1184 pub result: Result<Response, RpcError>,
1185}
1186
1187/// Handshake outcome: `HelloAck` or a typed refusal (spec §6 —
1188/// version skew is an error, not silence). Same `Ok`/`Err` wire shape
1189/// as [`Reply::result`]; refusals use [`RpcErrorCode::ProtocolMismatch`].
1190pub type HelloReply = Result<HelloAck, RpcError>;
1191
1192/// Structured RPC failure
1193// wire format: changing this is a breaking change
1194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1195pub struct RpcError {
1196 /// Machine-readable code
1197 pub code: RpcErrorCode,
1198 /// Human-readable message (plain English, no theme)
1199 pub message: String,
1200}
1201
1202/// Machine-readable RPC error codes
1203// wire format: changing existing variants is a breaking change
1204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1205#[serde(rename_all = "snake_case")]
1206#[non_exhaustive]
1207pub enum RpcErrorCode {
1208 /// Selector matched nothing
1209 NotFound,
1210 /// Config failed validation daemon-side
1211 InvalidConfig,
1212 /// Spawn failed (exec error, permissions)
1213 SpawnFailed,
1214 /// Handshake protocol version mismatch
1215 ProtocolMismatch,
1216 /// Unexpected daemon-side failure
1217 Internal,
1218 /// The request's deadline expired before the daemon finished it
1219 DeadlineExceeded,
1220}
1221
1222impl RpcErrorCode {
1223 /// Every variant, for code that needs to iterate them all.
1224 ///
1225 /// `#[non_exhaustive]` forces a `_` arm on any match written outside
1226 /// this crate, which would silently swallow a variant added here and
1227 /// never updated there (shep-cli's exit-code mapping test is the
1228 /// motivating case — see `crates/shep-cli/src/exit.rs`). Downstream
1229 /// crates should iterate `ALL` instead of hand-writing their own list
1230 /// that the compiler can't check.
1231 ///
1232 /// Kept honest by a private `assert_all_lists_every_variant` fn right
1233 /// below: read that doc for how a forgotten variant is caught here,
1234 /// where `#[non_exhaustive]` has no effect.
1235 pub const ALL: [Self; 6] = [
1236 Self::NotFound,
1237 Self::InvalidConfig,
1238 Self::SpawnFailed,
1239 Self::ProtocolMismatch,
1240 Self::Internal,
1241 Self::DeadlineExceeded,
1242 ];
1243
1244 /// Never called; exists purely so this crate fails to build if a
1245 /// variant is added to [`RpcErrorCode`] without also adding it to
1246 /// [`Self::ALL`].
1247 ///
1248 /// `#[non_exhaustive]` only forces a wildcard arm on matches written
1249 /// *outside* this crate — inside the crate that defines the enum, a
1250 /// match with no `_` arm is still checked for exhaustiveness (E0004),
1251 /// so a new variant breaks this build until it gets an arm here. Each
1252 /// arm indexes a fixed literal position into [`Self::ALL`], so growing
1253 /// the enum without growing the array is caught too: rustc denies an
1254 /// out-of-bounds constant array index by default.
1255 #[allow(dead_code)]
1256 const fn assert_all_lists_every_variant(code: Self) -> Self {
1257 match code {
1258 Self::NotFound => Self::ALL[0],
1259 Self::InvalidConfig => Self::ALL[1],
1260 Self::SpawnFailed => Self::ALL[2],
1261 Self::ProtocolMismatch => Self::ALL[3],
1262 Self::Internal => Self::ALL[4],
1263 Self::DeadlineExceeded => Self::ALL[5],
1264 }
1265 }
1266}
1267
1268#[cfg(test)]
1269mod tests {
1270 use super::*;
1271 use crate::config::AppConfig;
1272 use crate::protocol::PROTOCOL_VERSION;
1273 use crate::status::ProcStatus;
1274
1275 fn sample_info() -> ProcessInfo {
1276 ProcessInfo {
1277 id: 3,
1278 name: "web".to_string(),
1279 status: ProcStatus::Online,
1280 pid: Some(4242),
1281 restarts: 1,
1282 uptime_ms: 60_000,
1283 fold: Some("backend".to_string()),
1284 out_file: Some("/home/rin/.shep/logs/web-0-out.log".to_string()),
1285 err_file: Some("/home/rin/.shep/logs/web-0-err.log".to_string()),
1286 // 12.5 rather than a rounder-looking 12.3: an insta JSON
1287 // snapshot is only stable across platforms for a float the
1288 // binary representation holds exactly.
1289 cpu_percent: Some(12.5),
1290 memory_bytes: Some(48 * 1024 * 1024),
1291 dog: None,
1292 lambs: None,
1293 // `restarts: 1` above already says this sheep crashed once and
1294 // came back; a code rather than `None` is the honest exit that
1295 // caused it, not a fact this fixture invents.
1296 last_exit: Some(ExitInfo {
1297 code: Some(1),
1298 signal: None,
1299 }),
1300 smit: None,
1301 }
1302 }
1303
1304 /// fails if the builder's defaults drift from what a registered-but-not-yet
1305 /// running sheep actually looks like. A builder that quietly defaulted
1306 /// `uptime_ms` to something non-zero, or `restarts` to 1, would put a wrong
1307 /// number in front of an operator with nothing to compare it against.
1308 #[test]
1309 fn a_builder_with_nothing_set_is_a_sheep_that_has_not_run() {
1310 let info = ProcessInfo::builder(3, "web", ProcStatus::Stopped).build();
1311
1312 assert_eq!(info.id, 3);
1313 assert_eq!(info.name, "web");
1314 assert_eq!(info.status, ProcStatus::Stopped);
1315 assert_eq!(info.pid, None);
1316 assert_eq!(info.restarts, 0);
1317 assert_eq!(info.uptime_ms, 0);
1318 assert_eq!(info.fold, None);
1319 assert_eq!(info.out_file, None);
1320 assert_eq!(info.err_file, None);
1321 assert_eq!(info.cpu_percent, None);
1322 assert_eq!(info.memory_bytes, None);
1323 assert_eq!(info.dog, None);
1324 assert_eq!(info.lambs, None);
1325 assert_eq!(info.last_exit, None);
1326 }
1327
1328 /// fails if any setter writes a field other than its own — the failure a
1329 /// twelve-field builder is most likely to ship, and one no individual
1330 /// round-trip test would catch. Every field is given a value distinct from
1331 /// every other field's default, so a copy-pasted setter body shows up as a
1332 /// mismatch rather than as a coincidence.
1333 #[test]
1334 fn every_setter_writes_its_own_field_and_no_other() {
1335 let built = ProcessInfo::builder(3, "web", ProcStatus::Online)
1336 .pid(Some(4242))
1337 .restarts(1)
1338 .uptime_ms(60_000)
1339 .fold(Some("backend".to_string()))
1340 .out_file(Some("/home/rin/.shep/logs/web-0-out.log".to_string()))
1341 .err_file(Some("/home/rin/.shep/logs/web-0-err.log".to_string()))
1342 .cpu_percent(Some(12.5))
1343 .memory_bytes(Some(48 * 1024 * 1024))
1344 .dog(None)
1345 .last_exit(Some(ExitInfo {
1346 code: Some(1),
1347 signal: None,
1348 }))
1349 .build();
1350
1351 // `sample_info()` is still a struct literal, on purpose: it is the one
1352 // place in the workspace that names every field by hand, so this
1353 // comparison fails the day the struct grows a field the builder cannot
1354 // set. That is the point of comparing against it rather than against
1355 // another builder call.
1356 assert_eq!(built, sample_info());
1357
1358 // `dog` is the one field the comparison above cannot speak for, and it
1359 // is the field the whole dogs subsystem reads. `sample_info()`'s `dog`
1360 // is `None`, which is also the builder's default, so a `dog` setter with
1361 // an EMPTY BODY passes the assert_eq! above and passes it for the wrong
1362 // reason. `sample_info()` cannot be changed to `Some(..)` to fix that —
1363 // it feeds `reply_wire_snapshots` and `bus_event_wire_snapshots`, so
1364 // altering it moves pinned bytes. So the field gets its own line, with a
1365 // value nothing defaults to.
1366 assert_eq!(
1367 ProcessInfo::builder(1, "metrics", ProcStatus::Online)
1368 .dog(Some(DogSource::BuiltIn))
1369 .build()
1370 .dog,
1371 Some(DogSource::BuiltIn),
1372 "an empty `dog` setter body is invisible to the comparison above"
1373 );
1374
1375 // `lambs` is the second field the comparison above cannot speak for,
1376 // for the identical reason `dog` is the first: `sample_info()`'s value
1377 // is `None`, which is also the builder's default, so an EMPTY `lambs`
1378 // setter body passes the `assert_eq!` above. And `sample_info()` still
1379 // cannot be changed to a `Some(..)` — it feeds `reply_wire_snapshots`
1380 // and `bus_event_wire_snapshots`, so altering it moves pinned bytes.
1381 assert_eq!(
1382 ProcessInfo::builder(1, "web", ProcStatus::Online)
1383 .lambs(Some(vec![Lamb::new(4243, "node")]))
1384 .build()
1385 .lambs,
1386 Some(vec![Lamb::new(4243, "node")]),
1387 "an empty `lambs` setter body is invisible to the comparison above"
1388 );
1389
1390 // `smit` is the third, on the same terms, and it is the field a
1391 // third party writes — so an empty setter body here would silently
1392 // drop every dog's mark rather than merely lose a decoration.
1393 assert_eq!(
1394 ProcessInfo::builder(1, "web", ProcStatus::Online)
1395 .smit(Some("\u{25b2} main@a1b2c3".to_string()))
1396 .build()
1397 .smit
1398 .as_deref(),
1399 Some("\u{25b2} main@a1b2c3"),
1400 "an empty `smit` setter body is invisible to the comparison above"
1401 );
1402 }
1403
1404 /// fails if `lambs` collapses to a bare `Vec`. The three states are the point:
1405 /// a peer that predates the field and a reply that did not walk the tree are
1406 /// both `None`, and a sheep that really has no children is `Some(vec![])`. A
1407 /// `Vec` would render the first two as "this sheep has no lambs", which is a
1408 /// claim neither of them makes.
1409 #[test]
1410 fn lambs_distinguishes_not_walked_from_walked_and_empty() {
1411 let not_walked = ProcessInfo::builder(1, "web", ProcStatus::Online).build();
1412 assert_eq!(not_walked.lambs, None);
1413
1414 let walked_empty = ProcessInfo::builder(1, "web", ProcStatus::Online)
1415 .lambs(Some(Vec::new()))
1416 .build();
1417 assert_eq!(walked_empty.lambs, Some(Vec::new()));
1418 }
1419
1420 /// fails if a `ProcessInfo` from a daemon that predates the field stops
1421 /// deserializing. That is the whole reason the field is optional and the reason
1422 /// `PROTOCOL_VERSION` does not move for it — an old daemon's reply carries no
1423 /// `lambs` key at all, and a required field there would mean a new client could
1424 /// not list against an old daemon.
1425 #[test]
1426 fn a_process_info_without_a_lambs_key_still_deserializes() {
1427 let fixture = r#"{
1428 "id": 3, "name": "web", "status": "online", "pid": 4242,
1429 "restarts": 0, "uptime_ms": 100, "fold": null,
1430 "out_file": null, "err_file": null,
1431 "cpu_percent": null, "memory_bytes": null, "dog": null
1432 }"#;
1433 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
1434 assert_eq!(info.lambs, None);
1435 }
1436
1437 /// fails if a lamb stops carrying its name, or starts carrying a command line.
1438 /// The name is `sysinfo`'s executable name, never argv — argv routinely holds
1439 /// credentials (`--password=`, `?token=`) and `shep describe --format json` is
1440 /// output people paste into issues.
1441 #[test]
1442 fn a_lamb_is_a_pid_and_an_executable_name() {
1443 let lamb = Lamb::new(4243, "node");
1444 let json = serde_json::to_string(&lamb).unwrap();
1445 assert_eq!(json, r#"{"pid":4243,"name":"node"}"#);
1446 assert_eq!(serde_json::from_str::<Lamb>(&json).unwrap(), lamb);
1447 }
1448
1449 /// fails if `DogSource` loses its `tag = "kind"` or its snake_case
1450 /// rename, and fails if `Adopted`'s `path` is renamed — any of the three
1451 /// changes one of these two strings while every type-level test in this
1452 /// module keeps passing. The marker is what the CLI splits two tables on
1453 /// and what the metrics dog reports a health gauge from, so a silent
1454 /// rename here is a silently empty dogs table.
1455 #[test]
1456 fn a_dog_source_serializes_snake_case_under_its_kind() {
1457 assert_eq!(
1458 serde_json::to_string(&DogSource::BuiltIn).unwrap(),
1459 r#"{"kind":"built_in"}"#
1460 );
1461 let adopted = DogSource::Adopted {
1462 path: "/usr/local/bin/shep-otel".to_string(),
1463 };
1464 let wire = r#"{"kind":"adopted","path":"/usr/local/bin/shep-otel"}"#;
1465 assert_eq!(serde_json::to_string(&adopted).unwrap(), wire);
1466 assert_eq!(serde_json::from_str::<DogSource>(wire).unwrap(), adopted);
1467 }
1468
1469 /// fails if `dog` stops being optional. A daemon built before dogs
1470 /// sends a reply with no such key and still announces protocol 1, so a
1471 /// required field would make a current client unable to list against it
1472 /// at all — the same skew rule `out_file` and `cpu_percent` are pinned
1473 /// under, and the same committed-byte-fixture proof.
1474 #[test]
1475 fn v1_process_info_without_a_dog_marker_still_deserializes() {
1476 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}"#;
1477 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
1478 assert_eq!(info.dog, None);
1479 }
1480
1481 /// fails if `last_exit` stops being optional. A daemon built before this
1482 /// field sends a reply with no such key and still announces protocol 1 —
1483 /// the same skew rule every other field added after `Hello`/`HelloAck`
1484 /// were fixed is pinned under.
1485 ///
1486 /// This is also the empirical proof behind task 49's own open question:
1487 /// none of `ProcessInfo`'s fields carry `#[serde(default)]`, and there is
1488 /// no container-level one either, yet the doc comments on `out_file` and
1489 /// `cpu_percent` both claim "`None` only when the peer daemon predates
1490 /// this field" as though one existed. Serde's `Deserialize` derive
1491 /// special-cases a field whose type is syntactically `Option<...>`: a
1492 /// missing key resolves to `None` without `#[serde(default)]` doing
1493 /// anything, because the derive macro recognizes the `Option` wrapper
1494 /// itself and generates that fallback for it. Those doc comments were
1495 /// right; they just named the wrong mechanism, or none. This test pins
1496 /// the real one for `last_exit` specifically — with `dog` and `lambs`
1497 /// present but `last_exit` genuinely absent from the JSON below — rather
1498 /// than leaving it as an inference from `v1_process_info_without_a_dog_
1499 /// marker_still_deserializes` above.
1500 #[test]
1501 fn a_process_info_without_a_last_exit_key_still_deserializes() {
1502 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}"#;
1503 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
1504 assert_eq!(info.last_exit, None);
1505 }
1506
1507 /// fails if a `Signal` frame stops carrying the signal name as plain text, or
1508 /// if the outcome rows stop distinguishing their three cases. The name travels
1509 /// as a `String` on purpose (`AppConfig::kill_signal` does the same): the wire
1510 /// stays readable and the daemon re-validates, which it has to do anyway
1511 /// because peer input is untrusted.
1512 #[test]
1513 fn a_signal_request_and_its_reply_round_trip() {
1514 let request = Request::Signal {
1515 selector: SelectorSpec::Name("web".to_string()),
1516 signal: "SIGHUP".to_string(),
1517 };
1518 let json = serde_json::to_string(&request).unwrap();
1519 assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
1520
1521 let reply = Response::Signalled(vec![
1522 SignalReply {
1523 id: 1,
1524 name: "web".to_string(),
1525 outcome: SignalOutcome::Delivered,
1526 },
1527 SignalReply {
1528 id: 2,
1529 name: "web".to_string(),
1530 outcome: SignalOutcome::NotRunning,
1531 },
1532 SignalReply {
1533 id: 3,
1534 name: "api".to_string(),
1535 outcome: SignalOutcome::Failed {
1536 reason: "no such process".to_string(),
1537 },
1538 },
1539 ]);
1540 let json = serde_json::to_string(&reply).unwrap();
1541 assert_eq!(serde_json::from_str::<Response>(&json).unwrap(), reply);
1542 // The three tags, spelled out: a variant renamed in Rust changes these
1543 // strings mechanically, compiles clean, and breaks a client matching on
1544 // them with nothing to say why.
1545 assert!(json.contains(r#""kind":"delivered""#), "{json}");
1546 assert!(json.contains(r#""kind":"not_running""#), "{json}");
1547 assert!(json.contains(r#""kind":"failed""#), "{json}");
1548 }
1549
1550 /// fails if `Scale` grows a selector. It takes an app NAME, and that is the
1551 /// design: `instances` is a per-app number and instance slots are allocated
1552 /// per name-group, so `shep stock /web.*/ 4` would have to mean either four
1553 /// each or four total and there is no reading of it that is not a guess.
1554 #[test]
1555 fn a_scale_request_names_one_app_and_a_count() {
1556 let request = Request::Scale {
1557 name: "web".to_string(),
1558 count: 4,
1559 };
1560 let json = serde_json::to_string(&request).unwrap();
1561 assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
1562 assert!(json.contains(r#""kind":"scale""#), "{json}");
1563 assert!(json.contains(r#""name":"web""#), "{json}");
1564 // No `selector` key at all — the shape that says this verb is not one of
1565 // the selector-taking family.
1566 assert!(!json.contains("selector"), "{json}");
1567 }
1568
1569 /// fails if `Scaled` stops being distinguishable from the eight other replies
1570 /// carrying a bare `Vec<ProcessInfo>`. Each of those names which request it
1571 /// answers precisely so it can diverge later without a protocol bump — the
1572 /// enum's own doc says not to collapse them, and this is the test that notices.
1573 #[test]
1574 fn a_scaled_reply_carries_its_own_tag() {
1575 let json = serde_json::to_string(&Response::Scaled(vec![])).unwrap();
1576 assert_eq!(json, r#"{"kind":"scaled","data":[]}"#);
1577 }
1578
1579 /// fails if the three outcomes stop being tellable apart on the wire, or if
1580 /// `NotWritten` stops carrying its reason. That reason is the only thing that
1581 /// distinguishes "the app is not reading its stdin" from "the pipe broke", and
1582 /// the operator's next move differs between them.
1583 #[test]
1584 fn a_send_line_request_and_its_reply_round_trip() {
1585 let request = Request::SendLine {
1586 selector: SelectorSpec::Name("repl".to_string()),
1587 line: "reload-config".to_string(),
1588 };
1589 let json = serde_json::to_string(&request).unwrap();
1590 assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
1591
1592 let reply = Response::SentLine(vec![
1593 LineReply {
1594 id: 1,
1595 name: "repl".to_string(),
1596 outcome: LineOutcome::Sent,
1597 },
1598 LineReply {
1599 id: 2,
1600 name: "web".to_string(),
1601 outcome: LineOutcome::NoStdin,
1602 },
1603 LineReply {
1604 id: 3,
1605 name: "stuck".to_string(),
1606 outcome: LineOutcome::NotWritten {
1607 reason: "the app did not read its stdin within 2s".to_string(),
1608 },
1609 },
1610 ]);
1611 let json = serde_json::to_string(&reply).unwrap();
1612 assert_eq!(serde_json::from_str::<Response>(&json).unwrap(), reply);
1613 assert!(json.contains(r#""kind":"sent""#), "{json}");
1614 assert!(json.contains(r#""kind":"no_stdin""#), "{json}");
1615 assert!(json.contains("did not read its stdin"), "{json}");
1616 }
1617
1618 /// fails if a newline can ride inside the line. The wire carries ONE line and
1619 /// the writer appends the terminator, so an embedded newline would deliver two
1620 /// commands where the operator typed one — the shape that turns a typo into an
1621 /// unintended second instruction to a REPL.
1622 #[test]
1623 fn a_line_carrying_a_newline_is_still_one_field_on_the_wire() {
1624 let request = Request::SendLine {
1625 selector: SelectorSpec::All,
1626 line: "a\nb".to_string(),
1627 };
1628 let json = serde_json::to_string(&request).unwrap();
1629 // Escaped, not literal: the frame stays one JSON object. Rejecting it is
1630 // the daemon's job (see `shep whisper`), not serde's, and this pins that
1631 // the wire itself does not quietly split it.
1632 assert!(json.contains(r#""line":"a\nb""#), "{json}");
1633 assert_eq!(serde_json::from_str::<Request>(&json).unwrap(), request);
1634 }
1635
1636 #[test]
1637 fn request_wire_snapshots() {
1638 let requests = vec![
1639 Envelope {
1640 id: 1,
1641 deadline_ms: Some(5000),
1642 body: Request::Ping,
1643 },
1644 Envelope {
1645 id: 2,
1646 deadline_ms: None,
1647 body: Request::ListFlock,
1648 },
1649 Envelope {
1650 id: 3,
1651 deadline_ms: None,
1652 body: Request::Stop {
1653 selector: SelectorSpec::Name("web".to_string()),
1654 },
1655 },
1656 Envelope {
1657 id: 4,
1658 deadline_ms: None,
1659 body: Request::Start {
1660 apps: vec![AppConfig::minimal("web", "./srv")],
1661 },
1662 },
1663 // `All` rather than a named sheep: it is the selector `shep
1664 // reopen` sends when given no argument, and the one a signal can
1665 // ever mean, so it is the row worth pinning.
1666 Envelope {
1667 id: 5,
1668 deadline_ms: None,
1669 body: Request::Reopen {
1670 selector: SelectorSpec::All,
1671 },
1672 },
1673 // Deliberately the same selector as the row above, so the two
1674 // log-plane rows differ by their `kind` and by nothing else: a
1675 // `Flush` that serialized under `reopen`'s tag — the shape a
1676 // copy-pasted variant takes — shows up here as two identical
1677 // objects rather than as a diff a reader has to compare field by
1678 // field. `shep flush` demands an explicit selector, so `all` is
1679 // not a default here the way it is for `reopen`; it is simply the
1680 // widest thing an operator can type.
1681 Envelope {
1682 id: 6,
1683 deadline_ms: None,
1684 body: Request::Flush {
1685 selector: SelectorSpec::All,
1686 },
1687 },
1688 // The same selector as the `stop` row above, for the reason the
1689 // pair above share theirs: `reload` is the third verb that
1690 // demands an explicit selector and replaces what it matches, so
1691 // the variant it would be copy-pasted from is `stop`. Serialized
1692 // under `stop`'s tag it shows up here as two identical objects
1693 // rather than as a diff a reader has to compare field by field.
1694 Envelope {
1695 id: 7,
1696 deadline_ms: None,
1697 body: Request::Reload {
1698 selector: SelectorSpec::Name("web".to_string()),
1699 },
1700 },
1701 // `action`/`params` here match the spec's own §9 example
1702 // (`trigger web set-log-level debug`) and channel.rs's
1703 // with-params fixture verbatim, so a reader tracing a trigger
1704 // from the CLI through the client↔daemon wire to the fd-3 wire
1705 // sees the same two strings at every hop rather than three
1706 // unrelated examples.
1707 Envelope {
1708 id: 8,
1709 deadline_ms: None,
1710 body: Request::Trigger {
1711 selector: SelectorSpec::Name("web".to_string()),
1712 action: "set-log-level".to_string(),
1713 params: Some("debug".to_string()),
1714 },
1715 },
1716 // The first fieldless verb added since `Ping`/`ListFlock`, and
1717 // pinned for that reason: a fieldless variant serializes as a
1718 // bare `{"kind":"..."}` with no `selector` key at all, so a
1719 // reader comparing this row against `stop`'s sees the whole
1720 // difference between the two shapes in one place.
1721 Envelope {
1722 id: 9,
1723 deadline_ms: None,
1724 body: Request::SaveRoll,
1725 },
1726 // Paired with the `save_roll` row above so the two halves of the
1727 // roll — the direction that writes it and the direction that
1728 // assembles from it — sit next to each other, differing by their
1729 // `kind` and by nothing else.
1730 Envelope {
1731 id: 10,
1732 deadline_ms: None,
1733 body: Request::Muster,
1734 },
1735 // The three dog verbs together, in the order an operator meets
1736 // them: ask for a section, start a dog, stop one. Adjacent on
1737 // purpose — `enable_dog` and `disable_dog` differ by their
1738 // `kind` and by `source`, so a `DisableDog` accidentally given
1739 // `EnableDog`'s tag shows up here as two near-identical objects
1740 // rather than as a diff a reader has to compare field by field.
1741 Envelope {
1742 id: 11,
1743 deadline_ms: None,
1744 body: Request::DogConfig {
1745 name: "bark".to_string(),
1746 },
1747 },
1748 Envelope {
1749 id: 12,
1750 deadline_ms: None,
1751 body: Request::EnableDog {
1752 name: "metrics".to_string(),
1753 source: DogSource::BuiltIn,
1754 },
1755 },
1756 Envelope {
1757 id: 13,
1758 deadline_ms: None,
1759 body: Request::DisableDog {
1760 name: "metrics".to_string(),
1761 },
1762 },
1763 // The three selector shapes no fixture reached before Phase 10.
1764 // Grouped and adjacent on purpose: `Id`, `Regex` and `Fold` are
1765 // three newtypes over three different inner types, and the wire
1766 // tells them apart only by their own `kind` tag — a `Fold` that
1767 // serialized under `regex`'s tag is a `shep restart fold:api`
1768 // that silently becomes a regex match, which is a wrong set of
1769 // sheep restarted and not an error anyone sees.
1770 Envelope {
1771 id: 14,
1772 deadline_ms: None,
1773 body: Request::Describe {
1774 selector: SelectorSpec::Id(7),
1775 },
1776 },
1777 Envelope {
1778 id: 15,
1779 deadline_ms: None,
1780 body: Request::Describe {
1781 selector: SelectorSpec::Regex("^web-".to_string()),
1782 },
1783 },
1784 Envelope {
1785 id: 16,
1786 deadline_ms: None,
1787 body: Request::Describe {
1788 selector: SelectorSpec::Fold("api".to_string()),
1789 },
1790 },
1791 // `SIGHUP` rather than `SIGTERM`: TERM is what the stop ladder
1792 // already sends, so a fixture using it could not tell a `signal`
1793 // frame from a stop's. HUP is the signal this verb exists for.
1794 Envelope {
1795 id: 17,
1796 deadline_ms: None,
1797 body: Request::Signal {
1798 selector: SelectorSpec::Name("web".to_string()),
1799 signal: "SIGHUP".to_string(),
1800 },
1801 },
1802 // The one verb in this enum whose body has no `selector` key at
1803 // all — a reader comparing this row against `stop`'s sees the
1804 // whole difference in one place.
1805 Envelope {
1806 id: 18,
1807 deadline_ms: None,
1808 body: Request::Scale {
1809 name: "web".to_string(),
1810 count: 4,
1811 },
1812 },
1813 // `SelectorSpec::All` rather than a named sheep, mirroring the
1814 // `reopen`/`flush` rows above: it is the widest thing an operator
1815 // can type, and the line carries no terminator on the wire — the
1816 // shepherd appends it — so a fixture with one proves that half of
1817 // the contract too.
1818 Envelope {
1819 id: 19,
1820 deadline_ms: None,
1821 body: Request::SendLine {
1822 selector: SelectorSpec::All,
1823 line: "reload-config".to_string(),
1824 },
1825 },
1826 // The second verb here with no `selector` key, and the only one
1827 // whose payload a third party writes. Both halves of its
1828 // `Option` are pinned — a paint and a clear — because a dog
1829 // author reading this fixture needs the clear frame's exact
1830 // shape and would otherwise have to guess `null`.
1831 Envelope {
1832 id: 20,
1833 deadline_ms: None,
1834 body: Request::SetSmit {
1835 sheep: "web".to_string(),
1836 smit: Some(
1837 "\u{25b2} main@a1b2c3"
1838 .parse()
1839 .expect("the reference smit is valid"),
1840 ),
1841 },
1842 },
1843 Envelope {
1844 id: 21,
1845 deadline_ms: None,
1846 body: Request::SetSmit {
1847 sheep: "web".to_string(),
1848 smit: None,
1849 },
1850 },
1851 ];
1852 insta::assert_json_snapshot!("request_wire_v1", requests);
1853 }
1854
1855 #[test]
1856 fn reply_wire_snapshots() {
1857 let replies = vec![
1858 Reply {
1859 id: 1,
1860 result: Ok(Response::Pong),
1861 },
1862 Reply {
1863 id: 2,
1864 result: Ok(Response::Flock(vec![sample_info()])),
1865 },
1866 Reply {
1867 id: 3,
1868 result: Err(RpcError {
1869 code: RpcErrorCode::NotFound,
1870 message: "no sheep matches `web`".to_string(),
1871 }),
1872 },
1873 // Unlike `Reopened`/`Flushed`/`Reloading` above (all wire-identical
1874 // to `Flock`, just under a different `kind` tag, so pinning `Flock`
1875 // once already covers their shape), `Triggered` carries a genuinely
1876 // different row — `ActionReply` is not a `ProcessInfo` — so it earns
1877 // its own entry. `Replied` is the struct-shaped variant of
1878 // `ActionOutcome`, and so the one worth pinning here: the three
1879 // unit variants serialize as bare `{"kind":"..."}`, a shape already
1880 // proven by every fieldless variant elsewhere on this wire.
1881 Reply {
1882 id: 4,
1883 result: Ok(Response::Triggered(vec![ActionReply {
1884 id: 3,
1885 name: "web".to_string(),
1886 outcome: ActionOutcome::Replied {
1887 body: "ok".to_string(),
1888 },
1889 }])),
1890 },
1891 // The only struct-shaped `Response` variant, so the one worth
1892 // pinning here: every other variant on this wire is a newtype
1893 // over a Vec or a unit, both shapes already proven above.
1894 Reply {
1895 id: 5,
1896 result: Ok(Response::RollSaved {
1897 path: "/home/rin/.shep/flock.json".to_string(),
1898 apps: 2,
1899 }),
1900 },
1901 // `sample_info()` above pins the absent marker (a sheep's
1902 // `"dog": null`); this row is the only place the present one is
1903 // pinned, and `Adopted` rather than `BuiltIn` because it is the
1904 // variant carrying a payload — the unit variant's shape is
1905 // already proven by every fieldless variant on this wire.
1906 Reply {
1907 id: 6,
1908 result: Ok(Response::Flock(vec![ProcessInfo {
1909 id: 7,
1910 name: "otel".to_string(),
1911 dog: Some(DogSource::Adopted {
1912 path: "/usr/local/bin/shep-otel".to_string(),
1913 }),
1914 ..sample_info()
1915 }])),
1916 },
1917 // The opaque blob, pinned as a blob: the daemon renders a TOML
1918 // table into a string and never a typed structure, so what this
1919 // row proves is that the section crosses the wire as text.
1920 Reply {
1921 id: 7,
1922 result: Ok(Response::DogSection {
1923 toml: "port = 9615\n".to_string().into(),
1924 }),
1925 },
1926 // The only `Response` variant carrying a BARE `ProcessInfo`
1927 // rather than a `Vec` of them: `enable` starts exactly one dog,
1928 // and a one-element list would invite a reader to wonder when it
1929 // holds two.
1930 Reply {
1931 id: 8,
1932 result: Ok(Response::DogStarted(ProcessInfo {
1933 id: 4,
1934 name: "metrics".to_string(),
1935 dog: Some(DogSource::BuiltIn),
1936 ..sample_info()
1937 })),
1938 },
1939 // The eleven variants no fixture reached before Phase 10. The
1940 // existing comment on the `Triggered` row is right that pinning
1941 // `Flock` once already proves the `Vec<ProcessInfo>` SHAPE — but
1942 // it does not prove any of these variants' own `kind` tags, and
1943 // three of them are not `Vec<ProcessInfo>`-shaped at all
1944 // (`Deleted` is a `Vec<u32>`, `Subscribed` and `ShuttingDown`
1945 // carry nothing). Each row below therefore carries the emptiest
1946 // legal body: what is being pinned here is the tag, and a body
1947 // repeated eight times would bury it.
1948 Reply {
1949 id: 9,
1950 result: Ok(Response::Described(vec![])),
1951 },
1952 Reply {
1953 id: 10,
1954 result: Ok(Response::Started(vec![])),
1955 },
1956 Reply {
1957 id: 11,
1958 result: Ok(Response::Stopped(vec![])),
1959 },
1960 Reply {
1961 id: 12,
1962 result: Ok(Response::Restarted(vec![])),
1963 },
1964 Reply {
1965 id: 13,
1966 result: Ok(Response::Reloading(vec![])),
1967 },
1968 Reply {
1969 id: 14,
1970 result: Ok(Response::Deleted(vec![7, 8])),
1971 },
1972 Reply {
1973 id: 15,
1974 result: Ok(Response::Reopened(vec![])),
1975 },
1976 Reply {
1977 id: 16,
1978 result: Ok(Response::Flushed(vec![])),
1979 },
1980 Reply {
1981 id: 17,
1982 result: Ok(Response::Mustered(vec![])),
1983 },
1984 Reply {
1985 id: 18,
1986 result: Ok(Response::Subscribed),
1987 },
1988 Reply {
1989 id: 19,
1990 result: Ok(Response::ShuttingDown),
1991 },
1992 // `Signalled`, mirroring the `Triggered` row above: three rows,
1993 // one per `SignalOutcome` variant, so a reader sees the whole
1994 // shape of the reply in one pinned fixture rather than one row
1995 // that happens to hit `Delivered` and leaves the other two tags
1996 // unproven.
1997 Reply {
1998 id: 20,
1999 result: Ok(Response::Signalled(vec![
2000 SignalReply {
2001 id: 1,
2002 name: "web".to_string(),
2003 outcome: SignalOutcome::Delivered,
2004 },
2005 SignalReply {
2006 id: 2,
2007 name: "web".to_string(),
2008 outcome: SignalOutcome::NotRunning,
2009 },
2010 SignalReply {
2011 id: 3,
2012 name: "api".to_string(),
2013 outcome: SignalOutcome::Failed {
2014 reason: "no such process".to_string(),
2015 },
2016 },
2017 ])),
2018 },
2019 Reply {
2020 id: 21,
2021 result: Ok(Response::Scaled(vec![sample_info()])),
2022 },
2023 // `SentLine`, mirroring the `Signalled` row above: three rows, one
2024 // per `LineOutcome` variant, so a reader sees the whole shape of
2025 // the reply in one pinned fixture rather than one row that
2026 // happens to hit `Sent` and leaves the other two tags unproven.
2027 Reply {
2028 id: 22,
2029 result: Ok(Response::SentLine(vec![
2030 LineReply {
2031 id: 1,
2032 name: "repl".to_string(),
2033 outcome: LineOutcome::Sent,
2034 },
2035 LineReply {
2036 id: 2,
2037 name: "web".to_string(),
2038 outcome: LineOutcome::NoStdin,
2039 },
2040 LineReply {
2041 id: 3,
2042 name: "stuck".to_string(),
2043 outcome: LineOutcome::NotWritten {
2044 reason: "the app did not read its stdin within 2s".to_string(),
2045 },
2046 },
2047 ])),
2048 },
2049 // A `Described` row with a real lamb tree. The `null` shape is pinned
2050 // on every other row here; this is the one that pins what a walked
2051 // sheep serializes as, which is the shape a `describe` consumer
2052 // actually parses.
2053 Reply {
2054 id: 23,
2055 result: Ok(Response::Described(vec![
2056 ProcessInfo::builder(3, "web", ProcStatus::Online)
2057 .pid(Some(4242))
2058 .lambs(Some(vec![Lamb::new(4243, "node"), Lamb::new(4244, "sh")]))
2059 .build(),
2060 ])),
2061 },
2062 // `sample_info()` pins `last_exit`'s "exited normally" shape
2063 // (`code` set, `signal` absent) on every row above; this is the
2064 // only place the other one — killed by a signal, `code` absent
2065 // — is pinned. `SIGTERM`'s raw number (15) rather than a
2066 // symbolic one, because [`ExitInfo::signal`]'s own doc says this
2067 // crate carries no name for it; naming one is a job for
2068 // whichever OS-aware layer renders this field.
2069 Reply {
2070 id: 24,
2071 result: Ok(Response::Flock(vec![
2072 ProcessInfo::builder(5, "worker", ProcStatus::Stopped)
2073 .restarts(1)
2074 .last_exit(Some(ExitInfo {
2075 code: None,
2076 signal: Some(15),
2077 }))
2078 .build(),
2079 ])),
2080 },
2081 // The one row that pins a smit on the wire. `sample_info()`
2082 // carries none, deliberately (see `every_setter_writes_its_own_
2083 // field_and_no_other` for why it cannot), so without this row
2084 // the field is pinned only in its absent shape — and the absent
2085 // shape is not the one a dog's reader has to parse.
2086 Reply {
2087 id: 25,
2088 result: Ok(Response::SmitPainted(vec![
2089 ProcessInfo::builder(3, "web", ProcStatus::Online)
2090 .pid(Some(4242))
2091 .smit(Some("\u{25b2} main@a1b2c3".to_string()))
2092 .build(),
2093 ])),
2094 },
2095 ];
2096 insta::assert_json_snapshot!("reply_wire_v1", replies);
2097 }
2098
2099 /// fails if the new field breaks an older peer, on the same terms as
2100 /// `last_exit` and `lambs` before it. A daemon that predates smits sends
2101 /// no `smit` key, and this decoding to `None` rather than erroring is
2102 /// what keeps `PROTOCOL_VERSION` at 1.
2103 #[test]
2104 fn a_process_info_without_a_smit_key_still_deserializes() {
2105 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}"#;
2106 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2107 assert_eq!(info.smit, None);
2108 }
2109
2110 /// fails if the daemon accepts a smit it should refuse. [`Smit`] must
2111 /// validate on the way IN, not only in `FromStr`: `docs/dogs.md` tells
2112 /// dog authors to speak this wire directly, so a dog written in another
2113 /// language never runs our parser.
2114 #[test]
2115 fn a_smit_is_validated_when_it_is_deserialized_not_only_when_parsed() {
2116 for bad in [
2117 r#""\u001b[2Jgone""#.to_string(), // an escape
2118 r#""a\nb""#.to_string(), // a newline
2119 r#""""#.to_string(), // empty
2120 r#"" ""#.to_string(), // whitespace
2121 format!(r#""{}""#, "x".repeat(Smit::MAX_CHARS + 1)), // too long
2122 ] {
2123 assert!(
2124 serde_json::from_str::<Smit>(&bad).is_err(),
2125 "a daemon must refuse this on the wire: {bad}"
2126 );
2127 }
2128 assert!(serde_json::from_str::<Smit>(r#""\u25b2 main@a1b2c3""#).is_ok());
2129 }
2130
2131 /// fails if a smit stops travelling as a bare JSON string. It is a
2132 /// newtype with a hand-written `Deserialize`, and the pair only agrees
2133 /// with itself if the serialize side stays transparent — a `Smit` that
2134 /// serialized as `{"0":"..."}` would round-trip through nothing.
2135 #[test]
2136 fn a_smit_travels_as_a_bare_string() {
2137 let smit: Smit = "\u{25b2} main@a1b2c3".parse().expect("valid");
2138 let json = serde_json::to_string(&smit).unwrap();
2139 assert_eq!(json, "\"\u{25b2} main@a1b2c3\"");
2140 assert_eq!(serde_json::from_str::<Smit>(&json).unwrap(), smit);
2141 }
2142
2143 /// fails if the cap starts counting bytes or display columns. Forty-eight
2144 /// CJK characters are 144 bytes and roughly 96 columns, and all three
2145 /// numbers disagree — a byte cap would refuse this legitimate smit at a
2146 /// third of its apparent length.
2147 #[test]
2148 fn a_smit_is_capped_in_characters_not_bytes() {
2149 let cjk = "\u{7f8a}".repeat(Smit::MAX_CHARS);
2150 assert_eq!(cjk.len(), Smit::MAX_CHARS * 3);
2151 assert!(cjk.parse::<Smit>().is_ok(), "{cjk}");
2152 assert_eq!(
2153 "x".repeat(Smit::MAX_CHARS + 1).parse::<Smit>(),
2154 Err(SmitError::TooLong {
2155 chars: Smit::MAX_CHARS + 1
2156 })
2157 );
2158 }
2159
2160 /// fails if a smit is repaired rather than refused. Trimming or stripping
2161 /// would hand an operator a mark its publisher never sent, and would put
2162 /// shep in the business of editing a string it has agreed not to
2163 /// understand.
2164 #[test]
2165 fn a_smit_is_stored_exactly_as_it_arrived() {
2166 let padded: Smit = " main@a1b2c3 ".parse().expect("valid");
2167 assert_eq!(padded.as_str(), " main@a1b2c3 ");
2168 assert_eq!(padded.to_string(), " main@a1b2c3 ");
2169 }
2170
2171 #[test]
2172 fn v1_fixture_still_deserializes() {
2173 // Committed byte fixture from protocol v1 — if this breaks, bump
2174 // PROTOCOL_VERSION and record it in the CHANGELOG (IR-35).
2175 let fixture = r#"{"id":7,"deadline_ms":null,"body":{"kind":"stop","selector":{"kind":"name","value":"web"}}}"#;
2176 let env: Envelope = serde_json::from_str(fixture).unwrap();
2177 assert_eq!(env.id, 7);
2178 assert!(matches!(
2179 env.body,
2180 Request::Stop { selector: SelectorSpec::Name(ref n) } if n == "web"
2181 ));
2182 }
2183
2184 #[test]
2185 fn hello_handshake_shape() {
2186 let hello = Hello {
2187 client_version: "0.1.0".to_string(),
2188 protocol: PROTOCOL_VERSION,
2189 };
2190 let json = serde_json::to_string(&hello).unwrap();
2191 assert_eq!(json, r#"{"client_version":"0.1.0","protocol":1}"#);
2192 }
2193
2194 #[test]
2195 fn hello_reply_carries_typed_skew_error() {
2196 let refusal: HelloReply = Err(RpcError {
2197 code: RpcErrorCode::ProtocolMismatch,
2198 message: "daemon speaks protocol 1, client sent 2".to_string(),
2199 });
2200 let json = serde_json::to_string(&refusal).unwrap();
2201 assert_eq!(
2202 json,
2203 r#"{"Err":{"code":"protocol_mismatch","message":"daemon speaks protocol 1, client sent 2"}}"#
2204 );
2205 let back: HelloReply = serde_json::from_str(&json).unwrap();
2206 assert_eq!(back, refusal);
2207 }
2208
2209 #[test]
2210 fn v1_reply_fixture_still_deserializes() {
2211 // Committed byte fixture, protocol v1 (IR-35).
2212 let ok = r#"{"id":1,"result":{"Ok":{"kind":"pong"}}}"#;
2213 let reply: Reply = serde_json::from_str(ok).unwrap();
2214 assert!(matches!(reply.result, Ok(Response::Pong)));
2215 let err = r#"{"id":2,"result":{"Err":{"code":"not_found","message":"no sheep"}}}"#;
2216 let reply: Reply = serde_json::from_str(err).unwrap();
2217 assert_eq!(reply.result.unwrap_err().code, RpcErrorCode::NotFound);
2218 }
2219
2220 #[test]
2221 fn v1_hello_ack_fixture_still_deserializes() {
2222 let fixture = r#"{"Ok":{"daemon_version":"0.1.0","protocol":1,"pid":4242}}"#;
2223 let ack: HelloReply = serde_json::from_str(fixture).unwrap();
2224 assert_eq!(ack.unwrap().pid, 4242);
2225 }
2226
2227 /// fails if the two fields stop being optional. A daemon built before
2228 /// them sends a reply with no such keys, and both peers still announce
2229 /// protocol 1 — a required field would make a current client unable to
2230 /// list against that daemon at all.
2231 #[test]
2232 fn v1_process_info_without_stats_still_deserializes() {
2233 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"}"#;
2234 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2235 assert_eq!(info.cpu_percent, None);
2236 assert_eq!(info.memory_bytes, None);
2237 }
2238
2239 #[test]
2240 fn v1_process_info_without_log_paths_still_deserializes() {
2241 // Committed byte fixture from before `out_file`/`err_file` existed
2242 // (IR-35). The handshake only compares PROTOCOL_VERSION, which this
2243 // addition deliberately did not bump, so a daemon built at this
2244 // vintage still connects to a current client and sends exactly these
2245 // bytes. Absent keys must land as `None`, not as a decode error.
2246 let fixture = r#"{"id":3,"name":"web","status":"online","pid":4242,"restarts":1,"uptime_ms":60000,"fold":"backend"}"#;
2247 let info: ProcessInfo = serde_json::from_str(fixture).unwrap();
2248 assert_eq!(info.id, 3);
2249 assert_eq!(info.out_file, None);
2250 assert_eq!(info.err_file, None);
2251 }
2252
2253 #[test]
2254 fn an_old_client_still_decodes_a_new_process_info() {
2255 // The other skew direction: a client built before the fields reads a
2256 // current daemon's reply. `ProcessInfo` carries no
2257 // `deny_unknown_fields` (unlike the config types in
2258 // `crate::config`), so the two extra keys are ignored rather than
2259 // refused — which is what makes this addition version-preserving.
2260 #[derive(Deserialize)]
2261 struct V1ProcessInfo {
2262 id: u32,
2263 fold: Option<String>,
2264 }
2265
2266 let current = serde_json::to_string(&sample_info()).unwrap();
2267 let old: V1ProcessInfo = serde_json::from_str(¤t).unwrap();
2268 assert_eq!(old.id, 3);
2269 assert_eq!(old.fold.as_deref(), Some("backend"));
2270 }
2271
2272 #[test]
2273 fn deadline_exceeded_code_serializes_snake_case() {
2274 // Additive variant (evolution rule): the existing codes keep their
2275 // strings, so v1 byte fixtures above still deserialize unchanged.
2276 assert_eq!(
2277 serde_json::to_string(&RpcErrorCode::DeadlineExceeded).unwrap(),
2278 "\"deadline_exceeded\""
2279 );
2280 assert_eq!(
2281 serde_json::from_str::<RpcErrorCode>("\"deadline_exceeded\"").unwrap(),
2282 RpcErrorCode::DeadlineExceeded
2283 );
2284 }
2285
2286 #[test]
2287 fn action_outcome_kinds_serialize_snake_case_and_round_trip() {
2288 // The shared snapshots above exercise exactly one `ActionOutcome`
2289 // variant (`Replied`, the only struct-shaped one, in
2290 // `reply_wire_snapshots`) — nothing else there would catch a rename
2291 // of `no_channel`, `skipped`, or `timed_out`. Pinned here instead,
2292 // the same way `deadline_exceeded_code_serializes_snake_case` pins a
2293 // lone `RpcErrorCode` variant above.
2294 let cases = [
2295 (
2296 ActionOutcome::Replied {
2297 body: "pong".to_string(),
2298 },
2299 r#"{"kind":"replied","body":"pong"}"#,
2300 ),
2301 (ActionOutcome::NoChannel, r#"{"kind":"no_channel"}"#),
2302 (ActionOutcome::Skipped, r#"{"kind":"skipped"}"#),
2303 (ActionOutcome::TimedOut, r#"{"kind":"timed_out"}"#),
2304 ];
2305 for (outcome, wire) in cases {
2306 assert_eq!(
2307 serde_json::to_string(&outcome).unwrap(),
2308 wire,
2309 "{outcome:?}"
2310 );
2311 assert_eq!(
2312 serde_json::from_str::<ActionOutcome>(wire).unwrap(),
2313 outcome
2314 );
2315 }
2316 }
2317
2318 /// fails if `SaveRoll` or `RollSaved` is given a `rename`, or if
2319 /// `Response`'s `content = "data"` is dropped — either changes these two
2320 /// strings while every type-level test in this module keeps passing.
2321 #[test]
2322 fn save_roll_serializes_snake_case_with_its_payload_under_data() {
2323 assert_eq!(
2324 serde_json::to_string(&Request::SaveRoll).unwrap(),
2325 r#"{"kind":"save_roll"}"#
2326 );
2327 let reply = Response::RollSaved {
2328 path: "/tmp/flock.json".to_string(),
2329 apps: 3,
2330 };
2331 let wire = r#"{"kind":"roll_saved","data":{"path":"/tmp/flock.json","apps":3}}"#;
2332 assert_eq!(serde_json::to_string(&reply).unwrap(), wire);
2333 assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), reply);
2334 }
2335
2336 /// fails if `Muster` or `Mustered` is given a `rename`, or if `Mustered`
2337 /// is declared fieldless — any of the three changes one of these two
2338 /// strings while every type-level test in this module keeps passing.
2339 ///
2340 /// The listing is empty on purpose. `Mustered` carries the same
2341 /// `Vec<ProcessInfo>` `Flock` does, and `reply_wire_snapshots` already
2342 /// pins that row field by field; what is unpinned until here is this
2343 /// variant's own tag and whether its payload lands under `data` at all.
2344 #[test]
2345 fn muster_serializes_snake_case_with_its_listing_under_data() {
2346 assert_eq!(
2347 serde_json::to_string(&Request::Muster).unwrap(),
2348 r#"{"kind":"muster"}"#
2349 );
2350 let reply = Response::Mustered(Vec::new());
2351 let wire = r#"{"kind":"mustered","data":[]}"#;
2352 assert_eq!(serde_json::to_string(&reply).unwrap(), wire);
2353 assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), reply);
2354 }
2355
2356 /// fails if any of the three verbs or either reply is given a `rename`,
2357 /// or if `Response`'s `content = "data"` is dropped. `disable_dog`'s
2358 /// answer is `Deleted`, which no other test in this module pairs with
2359 /// this verb — a handler wired to answer `Deleted` for `EnableDog` would
2360 /// still round-trip, and this is where the pairing is written down.
2361 #[test]
2362 fn the_dog_verbs_serialize_snake_case_with_their_payloads_under_data() {
2363 assert_eq!(
2364 serde_json::to_string(&Request::DogConfig {
2365 name: "bark".to_string()
2366 })
2367 .unwrap(),
2368 r#"{"kind":"dog_config","name":"bark"}"#
2369 );
2370 assert_eq!(
2371 serde_json::to_string(&Request::DisableDog {
2372 name: "bark".to_string()
2373 })
2374 .unwrap(),
2375 r#"{"kind":"disable_dog","name":"bark"}"#
2376 );
2377 let section = Response::DogSection {
2378 toml: "port = 9615\n".to_string().into(),
2379 };
2380 let wire = r#"{"kind":"dog_section","data":{"toml":"port = 9615\n"}}"#;
2381 assert_eq!(serde_json::to_string(§ion).unwrap(), wire);
2382 assert_eq!(serde_json::from_str::<Response>(wire).unwrap(), section);
2383 }
2384
2385 #[test]
2386 fn dog_section_toml_debug_does_not_leak() {
2387 // IR-41: a dog's `[dog.<name>]` section routinely holds webhook
2388 // credentials (a Discord/Slack URL with a bearer token embedded).
2389 // `Response` derives `Debug`, so this is the one thing standing
2390 // between that token and any future `tracing::debug!("{:?}", reply)`.
2391 // Exact string pinned so a lazy `#[derive(Debug)]` refactor on
2392 // `DogSectionToml` fails this test instead of silently reopening
2393 // the leak.
2394 let toml: DogSectionToml =
2395 "webhook_url = \"https://discord.com/api/webhooks/1/super-secret-token\"\n"
2396 .to_string()
2397 .into();
2398 assert_eq!(format!("{toml:?}"), "DogSectionToml(<70 bytes>)");
2399
2400 let response = Response::DogSection { toml };
2401 assert_eq!(
2402 format!("{response:?}"),
2403 "DogSection { toml: DogSectionToml(<70 bytes>) }"
2404 );
2405 }
2406}