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