shep_core/protocol/
frame.rs1use serde::{Deserialize, Serialize};
12
13use crate::protocol::{BusEvent, Reply};
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21#[serde(untagged)]
22#[non_exhaustive]
25pub enum ServerFrame {
26 Reply(Reply),
28 Event(BusEvent),
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35 use crate::protocol::{
36 BusEvent, ProcessEventKind, ProcessInfo, Reply, Response, RpcError, RpcErrorCode,
37 encode_frame,
38 };
39 use crate::status::ProcStatus;
40
41 fn sample_reply() -> Reply {
42 Reply {
43 id: 7,
44 result: Ok(Response::Pong),
45 }
46 }
47
48 fn sample_event() -> BusEvent {
49 BusEvent::Process {
50 event: ProcessEventKind::Online,
51 info: ProcessInfo {
52 id: 3,
53 name: "web".to_string(),
54 status: ProcStatus::Online,
55 pid: Some(4242),
56 restarts: 0,
57 uptime_ms: 0,
58 fold: None,
59 depends_on: Vec::new(),
60 out_file: Some("/home/ada/.shep/logs/web-0-out.log".to_string()),
61 err_file: Some("/home/ada/.shep/logs/web-0-err.log".to_string()),
62 cpu_percent: None,
63 memory_bytes: None,
64 dog: None,
65 lambs: None,
66 last_exit: None,
67 smit: None,
68 instance: None,
69 handshook: None,
70 dog_stale: None,
71 pending: None,
72 overridden: None,
73 max_memory: None,
74 },
75 manually: false,
76 at_ms: 1_700_000_000_000,
77 }
78 }
79
80 #[test]
81 fn server_frame_decodes_both_directions_of_the_stream() {
82 let reply = r#"{"id":1,"result":{"Ok":{"kind":"pong"}}}"#;
85 assert!(matches!(
86 serde_json::from_str::<ServerFrame>(reply).unwrap(),
87 ServerFrame::Reply(Reply { id: 1, .. })
88 ));
89 let event = r#"{"event":"log_out","data":{"id":3,"line":"ready"}}"#;
90 assert!(matches!(
91 serde_json::from_str::<ServerFrame>(event).unwrap(),
92 ServerFrame::Event(BusEvent::LogOut { id: 3, .. })
93 ));
94 }
95
96 #[test]
97 fn server_frame_is_byte_identical_to_its_payload() {
98 let reply = sample_reply();
101 assert_eq!(
102 encode_frame(&ServerFrame::Reply(reply.clone())).unwrap(),
103 encode_frame(&reply).unwrap()
104 );
105 let event = sample_event();
106 assert_eq!(
107 encode_frame(&ServerFrame::Event(event.clone())).unwrap(),
108 encode_frame(&event).unwrap()
109 );
110 }
111
112 #[test]
113 fn an_error_reply_still_decodes_as_a_reply_frame() {
114 let err = Reply {
115 id: 2,
116 result: Err(RpcError {
117 code: RpcErrorCode::DeadlineExceeded,
118 message: "request deadline of 5000 ms expired".to_string(),
119 daemon_version: None,
120 }),
121 };
122 let json = serde_json::to_string(&err).unwrap();
123 assert_eq!(
124 serde_json::from_str::<ServerFrame>(&json).unwrap(),
125 ServerFrame::Reply(err)
126 );
127 }
128}