Skip to main content

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                },
215                manually: false,
216                at_ms: 1_700_000_000_000,
217            },
218            BusEvent::LogOut {
219                id: 3,
220                line: "listening on :8080".to_string(),
221            },
222            BusEvent::Dropped { count: 17 },
223            // The row above pins `instance`'s absent shape; every lifecycle
224            // row below reuses it via `sample`. This is the only place the
225            // present shape (a live slot on a scaled app) is on the wire.
226            BusEvent::Process {
227                event: ProcessEventKind::Online,
228                info: ProcessInfo::builder(4, "web", ProcStatus::Online)
229                    .pid(Some(5150))
230                    .instance(Some(2))
231                    .build(),
232                manually: false,
233                at_ms: 1_700_000_000_000,
234            },
235        ];
236
237        // The lifecycle kinds exercised here (the reload trio has its own
238        // fixture), over one
239        // identical `info`, so the snapshot rows differ by their `event` tag
240        // and by nothing else. These are the ordinary events a real
241        // integration — a dashboard, a bark rule — depends on first, and a
242        // Rust-identifier rename on any of them would change the wire string
243        // mechanically, compile clean, and break that integration silently.
244        let sample = ProcessInfo::builder(3, "web", ProcStatus::WaitingRestart)
245            .restarts(2)
246            .uptime_ms(500)
247            .out_file(Some("/home/ada/.shep/logs/web-0-out.log".to_string()))
248            .err_file(Some("/home/ada/.shep/logs/web-0-err.log".to_string()))
249            // Reused below for `Stop` and `Delete` too — the two operator-
250            // caused endings, and proof that a `shep stop`/`shep delete`
251            // still carries the exit that produced them rather than losing
252            // it because an operator asked for it.
253            .last_exit(Some(ExitInfo {
254                code: Some(1),
255                signal: None,
256            }))
257            .build();
258
259        let lifecycle = [
260            ProcessEventKind::Start,
261            ProcessEventKind::Online,
262            ProcessEventKind::Restart,
263            ProcessEventKind::Stop,
264            ProcessEventKind::Delete,
265            ProcessEventKind::Errored,
266        ]
267        .map(|event| BusEvent::Process {
268            event,
269            info: sample.clone(),
270            manually: false,
271            at_ms: 1_700_000_000_000,
272        });
273
274        events.extend(lifecycle);
275
276        // All three shepherd-channel topics, over one sheep id, because the
277        // adjacent-tagged shape puts the message's own `kind` INSIDE `data`
278        // next to `id` — a nesting that is easy to get wrong by hand and
279        // invisible in a round-trip test, which only proves this crate agrees
280        // with itself.
281        events.extend([
282            BusEvent::Channel {
283                id: 3,
284                message: ChildMessage::Ready,
285            },
286            BusEvent::Channel {
287                id: 3,
288                message: ChildMessage::Metric {
289                    name: "rps".to_string(),
290                    value: 42.0,
291                },
292            },
293            BusEvent::Channel {
294                id: 3,
295                message: ChildMessage::ActionReply {
296                    action: "gc".to_string(),
297                    body: "freed 12MB".to_string(),
298                    id: Some(7),
299                },
300            },
301        ]);
302
303        insta::assert_json_snapshot!("bus_event_wire_v2", events);
304    }
305
306    #[test]
307    fn topics_follow_the_dotted_grammar() {
308        // spec §6: process.* / log.out / log.err / daemon.*
309        let e = BusEvent::LogOut {
310            id: 1,
311            line: String::new(),
312        };
313        assert_eq!(e.topic(), "log.out");
314        assert_eq!(BusEvent::DaemonShutdown.topic(), "daemon.shutdown");
315    }
316
317    /// The three kinds a reload reports itself with, pinned as topic strings
318    /// and as wire strings.
319    ///
320    /// Fails if [`BusEvent::topic`] maps any of them to the wrong dotted
321    /// string — a typo there is invisible to a `process.*` subscriber, which
322    /// matches anything under `process.`, and silently unreachable to one
323    /// that named the topic it wanted. Fails too if a variant's serde
324    /// spelling drifts from its snake_case default (a stray
325    /// `#[serde(rename)]`, or a variant renamed without its topic): a reload's
326    /// reply is an acceptance, so these frames are the whole of what a client
327    /// ever learns about how the reload went, and a client matching on the
328    /// wire string would stop recognising them.
329    #[test]
330    fn a_reload_reports_itself_under_three_topics() {
331        for (kind, topic, wire) in [
332            (ProcessEventKind::Reload, "process.reload", "\"reload\""),
333            (
334                ProcessEventKind::Reloaded,
335                "process.reloaded",
336                "\"reloaded\"",
337            ),
338            (
339                ProcessEventKind::ReloadAbandoned,
340                "process.reload_abandoned",
341                "\"reload_abandoned\"",
342            ),
343        ] {
344            let event = BusEvent::Process {
345                event: kind,
346                info: ProcessInfo {
347                    id: 3,
348                    name: "web".to_string(),
349                    status: ProcStatus::Stopping,
350                    pid: Some(4242),
351                    restarts: 0,
352                    uptime_ms: 0,
353                    fold: None,
354                    out_file: None,
355                    err_file: None,
356                    cpu_percent: None,
357                    memory_bytes: None,
358                    dog: None,
359                    lambs: None,
360                    last_exit: None,
361                    smit: None,
362                    instance: None,
363                },
364                manually: true,
365                at_ms: 0,
366            };
367            assert_eq!(event.topic(), topic, "{kind:?}");
368            assert_eq!(serde_json::to_string(&kind).unwrap(), wire, "{kind:?}");
369        }
370    }
371
372    #[test]
373    fn v1_bus_event_fixture_still_deserializes() {
374        // Adjacent-tagged shape pinned as a byte fixture (IR-35).
375        let fixture = r#"{"event":"log_out","data":{"id":3,"line":"ready"}}"#;
376        let ev: BusEvent = serde_json::from_str(fixture).unwrap();
377        assert!(matches!(ev, BusEvent::LogOut { id: 3, .. }));
378    }
379
380    /// fails if a shepherd-channel message maps to the wrong dotted topic. A
381    /// subscriber that asked for `channel.metric` and silently receives nothing
382    /// has no other way to find out, and `channel.*` matches whatever typo is
383    /// there — so the exact strings are the contract, not the prefix.
384    #[test]
385    fn every_shepherd_channel_message_has_its_own_topic() {
386        for (message, topic) in [
387            (ChildMessage::Ready, "channel.ready"),
388            (
389                ChildMessage::Metric {
390                    name: "rps".to_string(),
391                    value: 42.0,
392                },
393                "channel.metric",
394            ),
395            (
396                ChildMessage::ActionReply {
397                    action: "gc".to_string(),
398                    body: "ok".to_string(),
399                    id: Some(7),
400                },
401                "channel.action_reply",
402            ),
403        ] {
404            let event = BusEvent::Channel {
405                id: 3,
406                message: message.clone(),
407            };
408            assert_eq!(event.topic(), topic, "{message:?}");
409        }
410    }
411
412    /// fails if `channel.*` stops reaching every one of the three. The glob a
413    /// dashboard writes is the prefix, so a topic that drifted out from under it
414    /// (`channel_ready`, say) would be unreachable by the only pattern anyone
415    /// actually subscribes with.
416    #[test]
417    fn the_channel_glob_reaches_all_three_topics() {
418        for message in [
419            ChildMessage::Ready,
420            ChildMessage::Metric {
421                name: "rps".to_string(),
422                value: 1.0,
423            },
424            ChildMessage::ActionReply {
425                action: "gc".to_string(),
426                body: String::new(),
427                id: None,
428            },
429        ] {
430            let topic = BusEvent::Channel { id: 1, message }.topic();
431            assert!(
432                topic.starts_with("channel."),
433                "`{topic}` is not under the channel.* glob"
434            );
435        }
436    }
437
438    /// fails if the event stops carrying the message body. The whole argument for
439    /// putting the real message on the bus rather than a summary is that nothing
440    /// on this wire is a credential — a reply body that arrived truncated or
441    /// replaced would make the topic useless for the case it exists for, a
442    /// dashboard watching what apps actually say.
443    #[test]
444    fn a_channel_event_carries_the_message_verbatim() {
445        let event = BusEvent::Channel {
446            id: 3,
447            message: ChildMessage::ActionReply {
448                action: "gc".to_string(),
449                body: "freed 12MB".to_string(),
450                id: Some(7),
451            },
452        };
453        let json = serde_json::to_string(&event).unwrap();
454        assert!(json.contains("freed 12MB"), "{json}");
455        assert_eq!(serde_json::from_str::<BusEvent>(&json).unwrap(), event);
456    }
457}