shep_core/protocol/events.rs
1//! Bus events broadcast to subscribed clients
2
3use serde::{Deserialize, Serialize};
4
5use crate::protocol::channel::ChildMessage;
6use crate::protocol::request::ProcessInfo;
7
8/// What happened to a sheep
9// wire format: changing existing variants is a breaking change
10//
11// A NEW variant is additive for Rust and for the protocol version, but it is
12// not free for a subscriber that predates it, and this enum is the one place
13// in the protocol where that is true. There is no `#[serde(other)]` fallback,
14// and every variant's topic is `process.<something>`, which the `process.*`
15// glob an existing subscriber already uses matches — so an older client is
16// sent a frame it cannot decode. It drops that frame; it is not sent
17// anything it asked for and lost. The same does not arise for `Request` or
18// `Response`, where an old client never sends the verb whose answer it could
19// not read. Weigh that cost against the alternative before adding one:
20// reusing an existing kind and leaving subscribers to infer the event is the
21// other option, and it was the losing one for reload only because a reload's
22// reply is an acceptance, which leaves the bus as the only place its outcome
23// is ever reported.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26#[non_exhaustive]
27pub enum ProcessEventKind {
28 /// Spawn initiated
29 Start,
30 /// Became ready/online
31 Online,
32 /// Process exited
33 Exit,
34 /// Restart initiated
35 Restart,
36 /// A reload is replacing this instance: its replacement has been spawned
37 /// into the same instance slot, and this one will be asked to go once
38 /// that replacement is serving
39 Reload,
40 /// This instance has replaced the one it was spawned to drain, and that
41 /// one is gone — the swap is over
42 Reloaded,
43 /// A reload gave up, so the instances it had not reached are left alone
44 ///
45 /// The instance named is the one the abandonment left holding the slot,
46 /// and whether that one is serving depends on which abandonment it was.
47 /// Where the reload gave up on replacing an instance, that instance is
48 /// named and is still the app's live one. Where it gave up because the
49 /// replacement went down instead, the replacement is named. As with every
50 /// event here, `info` is that instance as it stood when the event was
51 /// raised, so read `info.status` rather than assuming a live one.
52 ReloadAbandoned,
53 /// Stopped by request
54 Stop,
55 /// Deregistered
56 Delete,
57 /// Restart budget exhausted
58 Errored,
59}
60
61/// One event on the daemon bus
62///
63/// Uses adjacently tagged serde format with `event` discriminator and `data` wrapper.
64/// Subscription TOPICS are the dotted strings from [`BusEvent::topic`]
65/// (`process.exit`, `log.out`, `daemon.*` — spec §6 grammar).
66/// The daemon's server-side filter globs against `topic()`.
67// wire format: changing existing variants is a breaking change
68#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
69// Adjacent tagging chosen because internally-tagged form cannot compile:
70// the `Process` variant has its own `event: ProcessEventKind` field, which
71// collides with an internal tag named `event` (serde_derive rejects this).
72// Adjacently tagging (with `content = "data"`) avoids the collision while
73// matching `Response`'s serde convention. Wire shape pinned by snapshot.
74#[serde(tag = "event", content = "data", rename_all = "snake_case")]
75#[non_exhaustive]
76pub enum BusEvent {
77 /// Lifecycle event for one sheep
78 Process {
79 /// What happened
80 event: ProcessEventKind,
81 /// Sheep snapshot at event time
82 info: ProcessInfo,
83 /// True when a user action caused it
84 manually: bool,
85 /// Unix millis
86 at_ms: u64,
87 },
88 /// One stdout line from a sheep
89 LogOut {
90 /// Sheep id
91 id: u32,
92 /// The line (no trailing newline)
93 line: String,
94 },
95 /// One stderr line from a sheep
96 LogErr {
97 /// Sheep id
98 id: u32,
99 /// The line
100 line: String,
101 },
102 /// One message a sheep wrote on its shepherd channel (fd 3).
103 ///
104 /// Child->shepherd only. The shepherd's own writes — the
105 /// `{"kind":"shutdown"}` of `shutdown_with_message`, and an `action` a
106 /// `Trigger` dispatched — are deliberately not here. Every one of them is
107 /// something an operator or the daemon just did and already has a
108 /// reporter: a shutdown message is followed by `process.stop`, and an
109 /// action is answered to the caller that sent it by
110 /// `Response::Triggered`. Putting them here as well would make this the
111 /// only event on the bus reporting a REQUEST rather than an outcome, and
112 /// would loop a dog that both subscribes and triggers back onto its own
113 /// dispatches. Adding the outbound half later stays additive — another
114 /// variant, more `channel.` topics, no version bump — so this is a
115 /// narrowing, not a door closed.
116 ///
117 /// `message` is the app's own text, whole and unredacted, unlike the
118 /// `[dog.<name>]` config that travels as [`DogSectionToml`]. Nothing on
119 /// this wire is a credential: `Ready` is empty, `Metric` is a name and a
120 /// float, and an `ActionReply` body is text the app chose to publish to
121 /// whoever triggered it. That is what makes a derived `Debug` safe here.
122 ///
123 /// [`DogSectionToml`]: crate::protocol::DogSectionToml
124 Channel {
125 /// The sheep that wrote it.
126 id: u32,
127 /// The message, exactly as it came off fd 3.
128 message: ChildMessage,
129 },
130 /// The bounded queue dropped this many events for this subscriber
131 Dropped {
132 /// Dropped-event count since last notice
133 count: u64,
134 },
135 /// Daemon is shutting down
136 DaemonShutdown,
137}
138
139impl BusEvent {
140 /// The dotted subscription topic for this event (spec §6 grammar)
141 #[must_use]
142 pub fn topic(&self) -> &'static str {
143 match self {
144 Self::Process { event, .. } => match event {
145 ProcessEventKind::Start => "process.start",
146 ProcessEventKind::Online => "process.online",
147 ProcessEventKind::Exit => "process.exit",
148 ProcessEventKind::Restart => "process.restart",
149 ProcessEventKind::Reload => "process.reload",
150 ProcessEventKind::Reloaded => "process.reloaded",
151 ProcessEventKind::ReloadAbandoned => "process.reload_abandoned",
152 ProcessEventKind::Stop => "process.stop",
153 ProcessEventKind::Delete => "process.delete",
154 ProcessEventKind::Errored => "process.errored",
155 },
156 Self::LogOut { .. } => "log.out",
157 Self::LogErr { .. } => "log.err",
158 // Total over `ChildMessage`, with no wildcard, and that is the
159 // point of leaving that enum exhaustive (see its module doc): a
160 // fourth kind on fd 3 fails to compile here until someone decides
161 // what its topic is, rather than defaulting into a topic no
162 // subscriber ever asked for.
163 Self::Channel { message, .. } => match message {
164 ChildMessage::Ready => "channel.ready",
165 ChildMessage::Metric { .. } => "channel.metric",
166 ChildMessage::ActionReply { .. } => "channel.action_reply",
167 },
168 Self::Dropped { .. } => "daemon.dropped",
169 Self::DaemonShutdown => "daemon.shutdown",
170 }
171 }
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177 use crate::protocol::request::{ExitInfo, ProcessInfo};
178 use crate::status::ProcStatus;
179
180 #[test]
181 fn bus_event_wire_snapshots() {
182 let mut events = vec![
183 BusEvent::Process {
184 event: ProcessEventKind::Exit,
185 info: ProcessInfo {
186 id: 3,
187 name: "web".to_string(),
188 status: ProcStatus::WaitingRestart,
189 pid: None,
190 restarts: 2,
191 uptime_ms: 500,
192 fold: None,
193 out_file: Some("/home/ada/.shep/logs/web-0-out.log".to_string()),
194 err_file: Some("/home/ada/.shep/logs/web-0-err.log".to_string()),
195 // A bus event is built from the actor's own snapshot,
196 // which never carries a resource reading.
197 cpu_percent: None,
198 memory_bytes: None,
199 dog: None,
200 lambs: None,
201 // `restarts: 2` already says this is not this sheep's
202 // first exit; `handle_exited` sets `last_exit` before it
203 // decides what to do with the exit, so the `Exit` event
204 // this row pins carries the very outcome it announces.
205 last_exit: Some(ExitInfo {
206 code: Some(1),
207 signal: None,
208 }),
209 // A non-ASCII marker on purpose: this snapshot is what
210 // pins the encoding a subscriber reads, and a smit is
211 // the one field on this row a third party writes.
212 smit: Some("\u{25b2} main@a1b2c3".to_string()),
213 instance: None,
214 handshook: None,
215 dog_stale: None,
216 },
217 manually: false,
218 at_ms: 1_700_000_000_000,
219 },
220 BusEvent::LogOut {
221 id: 3,
222 line: "listening on :8080".to_string(),
223 },
224 BusEvent::Dropped { count: 17 },
225 // The row above pins `instance`'s absent shape; every lifecycle
226 // row below reuses it via `sample`. This is the only place the
227 // present shape (a live slot on a scaled app) is on the wire.
228 BusEvent::Process {
229 event: ProcessEventKind::Online,
230 info: ProcessInfo::builder(4, "web", ProcStatus::Online)
231 .pid(Some(5150))
232 .instance(Some(2))
233 .build(),
234 manually: false,
235 at_ms: 1_700_000_000_000,
236 },
237 ];
238
239 // The lifecycle kinds exercised here (the reload trio has its own
240 // fixture), over one
241 // identical `info`, so the snapshot rows differ by their `event` tag
242 // and by nothing else. These are the ordinary events a real
243 // integration — a dashboard, a bark rule — depends on first, and a
244 // Rust-identifier rename on any of them would change the wire string
245 // mechanically, compile clean, and break that integration silently.
246 let sample = ProcessInfo::builder(3, "web", ProcStatus::WaitingRestart)
247 .restarts(2)
248 .uptime_ms(500)
249 .out_file(Some("/home/ada/.shep/logs/web-0-out.log".to_string()))
250 .err_file(Some("/home/ada/.shep/logs/web-0-err.log".to_string()))
251 // Reused below for `Stop` and `Delete` too — the two operator-
252 // caused endings, and proof that a `shep stop`/`shep delete`
253 // still carries the exit that produced them rather than losing
254 // it because an operator asked for it.
255 .last_exit(Some(ExitInfo {
256 code: Some(1),
257 signal: None,
258 }))
259 .build();
260
261 let lifecycle = [
262 ProcessEventKind::Start,
263 ProcessEventKind::Online,
264 ProcessEventKind::Restart,
265 ProcessEventKind::Stop,
266 ProcessEventKind::Delete,
267 ProcessEventKind::Errored,
268 ]
269 .map(|event| BusEvent::Process {
270 event,
271 info: sample.clone(),
272 manually: false,
273 at_ms: 1_700_000_000_000,
274 });
275
276 events.extend(lifecycle);
277
278 // All three shepherd-channel topics, over one sheep id, because the
279 // adjacent-tagged shape puts the message's own `kind` INSIDE `data`
280 // next to `id` — a nesting that is easy to get wrong by hand and
281 // invisible in a round-trip test, which only proves this crate agrees
282 // with itself.
283 events.extend([
284 BusEvent::Channel {
285 id: 3,
286 message: ChildMessage::Ready,
287 },
288 BusEvent::Channel {
289 id: 3,
290 message: ChildMessage::Metric {
291 name: "rps".to_string(),
292 value: 42.0,
293 },
294 },
295 BusEvent::Channel {
296 id: 3,
297 message: ChildMessage::ActionReply {
298 action: "gc".to_string(),
299 body: "freed 12MB".to_string(),
300 id: Some(7),
301 },
302 },
303 ]);
304
305 insta::assert_json_snapshot!("bus_event_wire_v2", events);
306 }
307
308 #[test]
309 fn topics_follow_the_dotted_grammar() {
310 // spec §6: process.* / log.out / log.err / daemon.*
311 let e = BusEvent::LogOut {
312 id: 1,
313 line: String::new(),
314 };
315 assert_eq!(e.topic(), "log.out");
316 assert_eq!(BusEvent::DaemonShutdown.topic(), "daemon.shutdown");
317 }
318
319 /// The three kinds a reload reports itself with, pinned as topic strings
320 /// and as wire strings.
321 ///
322 /// Fails if [`BusEvent::topic`] maps any of them to the wrong dotted
323 /// string — a typo there is invisible to a `process.*` subscriber, which
324 /// matches anything under `process.`, and silently unreachable to one
325 /// that named the topic it wanted. Fails too if a variant's serde
326 /// spelling drifts from its snake_case default (a stray
327 /// `#[serde(rename)]`, or a variant renamed without its topic): a reload's
328 /// reply is an acceptance, so these frames are the whole of what a client
329 /// ever learns about how the reload went, and a client matching on the
330 /// wire string would stop recognising them.
331 #[test]
332 fn a_reload_reports_itself_under_three_topics() {
333 for (kind, topic, wire) in [
334 (ProcessEventKind::Reload, "process.reload", "\"reload\""),
335 (
336 ProcessEventKind::Reloaded,
337 "process.reloaded",
338 "\"reloaded\"",
339 ),
340 (
341 ProcessEventKind::ReloadAbandoned,
342 "process.reload_abandoned",
343 "\"reload_abandoned\"",
344 ),
345 ] {
346 let event = BusEvent::Process {
347 event: kind,
348 info: ProcessInfo {
349 id: 3,
350 name: "web".to_string(),
351 status: ProcStatus::Stopping,
352 pid: Some(4242),
353 restarts: 0,
354 uptime_ms: 0,
355 fold: None,
356 out_file: None,
357 err_file: None,
358 cpu_percent: None,
359 memory_bytes: None,
360 dog: None,
361 lambs: None,
362 last_exit: None,
363 smit: None,
364 instance: None,
365 handshook: None,
366 dog_stale: None,
367 },
368 manually: true,
369 at_ms: 0,
370 };
371 assert_eq!(event.topic(), topic, "{kind:?}");
372 assert_eq!(serde_json::to_string(&kind).unwrap(), wire, "{kind:?}");
373 }
374 }
375
376 #[test]
377 fn v1_bus_event_fixture_still_deserializes() {
378 // Adjacent-tagged shape pinned as a byte fixture (IR-35).
379 let fixture = r#"{"event":"log_out","data":{"id":3,"line":"ready"}}"#;
380 let ev: BusEvent = serde_json::from_str(fixture).unwrap();
381 assert!(matches!(ev, BusEvent::LogOut { id: 3, .. }));
382 }
383
384 /// fails if a shepherd-channel message maps to the wrong dotted topic. A
385 /// subscriber that asked for `channel.metric` and silently receives nothing
386 /// has no other way to find out, and `channel.*` matches whatever typo is
387 /// there — so the exact strings are the contract, not the prefix.
388 #[test]
389 fn every_shepherd_channel_message_has_its_own_topic() {
390 for (message, topic) in [
391 (ChildMessage::Ready, "channel.ready"),
392 (
393 ChildMessage::Metric {
394 name: "rps".to_string(),
395 value: 42.0,
396 },
397 "channel.metric",
398 ),
399 (
400 ChildMessage::ActionReply {
401 action: "gc".to_string(),
402 body: "ok".to_string(),
403 id: Some(7),
404 },
405 "channel.action_reply",
406 ),
407 ] {
408 let event = BusEvent::Channel {
409 id: 3,
410 message: message.clone(),
411 };
412 assert_eq!(event.topic(), topic, "{message:?}");
413 }
414 }
415
416 /// fails if `channel.*` stops reaching every one of the three. The glob a
417 /// dashboard writes is the prefix, so a topic that drifted out from under it
418 /// (`channel_ready`, say) would be unreachable by the only pattern anyone
419 /// actually subscribes with.
420 #[test]
421 fn the_channel_glob_reaches_all_three_topics() {
422 for message in [
423 ChildMessage::Ready,
424 ChildMessage::Metric {
425 name: "rps".to_string(),
426 value: 1.0,
427 },
428 ChildMessage::ActionReply {
429 action: "gc".to_string(),
430 body: String::new(),
431 id: None,
432 },
433 ] {
434 let topic = BusEvent::Channel { id: 1, message }.topic();
435 assert!(
436 topic.starts_with("channel."),
437 "`{topic}` is not under the channel.* glob"
438 );
439 }
440 }
441
442 /// fails if the event stops carrying the message body. The whole argument for
443 /// putting the real message on the bus rather than a summary is that nothing
444 /// on this wire is a credential — a reply body that arrived truncated or
445 /// replaced would make the topic useless for the case it exists for, a
446 /// dashboard watching what apps actually say.
447 #[test]
448 fn a_channel_event_carries_the_message_verbatim() {
449 let event = BusEvent::Channel {
450 id: 3,
451 message: ChildMessage::ActionReply {
452 action: "gc".to_string(),
453 body: "freed 12MB".to_string(),
454 id: Some(7),
455 },
456 };
457 let json = serde_json::to_string(&event).unwrap();
458 assert!(json.contains("freed 12MB"), "{json}");
459 assert_eq!(serde_json::from_str::<BusEvent>(&json).unwrap(), event);
460 }
461}