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