rodecaster_protocol/
session.rs1use crate::change_frame::{decode, ChangeFrame};
24use crate::commands::EncodeError;
25use crate::events::{decode_event_from_frame, extract_initial_state};
26use crate::layout::BuildError;
27use crate::{Command, DeviceCapabilities, DeviceEvent, Layout};
28
29#[derive(Debug, Clone, PartialEq)]
31pub enum SessionUpdate {
32 Ready {
34 initial_events: Vec<DeviceEvent>,
36 },
37 Event(DeviceEvent),
39 NeedsFullSync,
42}
43
44#[derive(Debug)]
46pub enum SessionError {
47 Decode,
49 Layout(BuildError),
51 NotReady,
53 Encode(EncodeError),
55}
56
57impl std::fmt::Display for SessionError {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 match self {
60 SessionError::Decode => f.write_str("invalid or incomplete protocol payload"),
61 SessionError::Layout(error) => write!(f, "could not build device layout: {error}"),
62 SessionError::NotReady => f.write_str("protocol session needs a full sync"),
63 SessionError::Encode(error) => write!(f, "could not encode command: {error}"),
64 }
65 }
66}
67
68impl std::error::Error for SessionError {
69 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
70 match self {
71 SessionError::Layout(error) => Some(error),
72 SessionError::Encode(error) => Some(error),
73 SessionError::Decode | SessionError::NotReady => None,
74 }
75 }
76}
77
78#[derive(Debug, Default)]
80pub struct ProtocolSession {
81 layout: Option<Layout>,
82 capabilities: Option<DeviceCapabilities>,
83}
84
85impl ProtocolSession {
86 pub fn new() -> Self {
88 Self::default()
89 }
90
91 pub fn is_ready(&self) -> bool {
93 self.layout.is_some()
94 }
95
96 pub fn capabilities(&self) -> Option<&DeviceCapabilities> {
98 self.capabilities.as_ref()
99 }
100
101 pub fn layout(&self) -> Option<&Layout> {
103 self.layout.as_ref()
104 }
105
106 pub fn reset(&mut self) {
108 self.layout = None;
109 self.capabilities = None;
110 }
111
112 pub fn ingest(&mut self, payload: &[u8]) -> Result<SessionUpdate, SessionError> {
114 let frame = decode(payload).ok_or(SessionError::Decode)?;
115 match frame {
116 ChangeFrame::FullSync { root } => {
117 self.reset();
121 let layout = Layout::from_full_sync(&root).map_err(SessionError::Layout)?;
122 let capabilities = DeviceCapabilities::discover(&root, &layout);
123 let initial_events = extract_initial_state(&root, &layout);
124 self.layout = Some(layout);
125 self.capabilities = Some(capabilities);
126 Ok(SessionUpdate::Ready { initial_events })
127 }
128 ChangeFrame::ChildAdded { .. }
129 | ChangeFrame::ChildRemoved { .. }
130 | ChangeFrame::ChildMoved { .. } => {
131 self.reset();
132 Ok(SessionUpdate::NeedsFullSync)
133 }
134 ChangeFrame::PropertyChanged { .. } | ChangeFrame::PropertyRemoved { .. } => {
135 let layout = self.layout.as_ref().ok_or(SessionError::NotReady)?;
136 let event = decode_event_from_frame(frame, layout);
137 Ok(SessionUpdate::Event(event))
138 }
139 }
140 }
141
142 pub fn encode(&self, command: &Command) -> Result<Vec<Vec<u8>>, SessionError> {
144 let layout = self.layout.as_ref().ok_or(SessionError::NotReady)?;
145 command.encode(layout).map_err(SessionError::Encode)
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use crate::change_frame::encode_property_changed;
153 use crate::Value;
154
155 #[test]
156 fn rejects_incremental_event_before_full_sync() {
157 let mut session = ProtocolSession::new();
158 let payload = encode_property_changed(&[], "property", &Value::Bool(true));
159 assert!(matches!(
160 session.ingest(&payload),
161 Err(SessionError::NotReady)
162 ));
163 }
164
165 #[test]
166 fn structural_change_invalidates_session() {
167 let mut session = ProtocolSession::new();
168 let child_moved = [0x05, 0x00, 0x01, 0x00, 0x01, 0x01];
171 assert_eq!(
172 session.ingest(&child_moved).unwrap(),
173 SessionUpdate::NeedsFullSync
174 );
175 assert!(!session.is_ready());
176 }
177}