use crate::change_frame::{decode, ChangeFrame};
use crate::commands::EncodeError;
use crate::events::{decode_event_from_frame, extract_initial_state};
use crate::layout::BuildError;
use crate::{Command, DeviceCapabilities, DeviceEvent, Layout};
#[derive(Debug, Clone, PartialEq)]
pub enum SessionUpdate {
Ready {
initial_events: Vec<DeviceEvent>,
},
Event(DeviceEvent),
NeedsFullSync,
}
#[derive(Debug)]
pub enum SessionError {
Decode,
Layout(BuildError),
NotReady,
Encode(EncodeError),
}
impl std::fmt::Display for SessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SessionError::Decode => f.write_str("invalid or incomplete protocol payload"),
SessionError::Layout(error) => write!(f, "could not build device layout: {error}"),
SessionError::NotReady => f.write_str("protocol session needs a full sync"),
SessionError::Encode(error) => write!(f, "could not encode command: {error}"),
}
}
}
impl std::error::Error for SessionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
SessionError::Layout(error) => Some(error),
SessionError::Encode(error) => Some(error),
SessionError::Decode | SessionError::NotReady => None,
}
}
}
#[derive(Debug, Default)]
pub struct ProtocolSession {
layout: Option<Layout>,
capabilities: Option<DeviceCapabilities>,
}
impl ProtocolSession {
pub fn new() -> Self {
Self::default()
}
pub fn is_ready(&self) -> bool {
self.layout.is_some()
}
pub fn capabilities(&self) -> Option<&DeviceCapabilities> {
self.capabilities.as_ref()
}
pub fn layout(&self) -> Option<&Layout> {
self.layout.as_ref()
}
pub fn reset(&mut self) {
self.layout = None;
self.capabilities = None;
}
pub fn ingest(&mut self, payload: &[u8]) -> Result<SessionUpdate, SessionError> {
let frame = decode(payload).ok_or(SessionError::Decode)?;
match frame {
ChangeFrame::FullSync { root } => {
self.reset();
let layout = Layout::from_full_sync(&root).map_err(SessionError::Layout)?;
let capabilities = DeviceCapabilities::discover(&root, &layout);
let initial_events = extract_initial_state(&root, &layout);
self.layout = Some(layout);
self.capabilities = Some(capabilities);
Ok(SessionUpdate::Ready { initial_events })
}
ChangeFrame::ChildAdded { .. }
| ChangeFrame::ChildRemoved { .. }
| ChangeFrame::ChildMoved { .. } => {
self.reset();
Ok(SessionUpdate::NeedsFullSync)
}
ChangeFrame::PropertyChanged { .. } | ChangeFrame::PropertyRemoved { .. } => {
let layout = self.layout.as_ref().ok_or(SessionError::NotReady)?;
let event = decode_event_from_frame(frame, layout);
Ok(SessionUpdate::Event(event))
}
}
}
pub fn encode(&self, command: &Command) -> Result<Vec<Vec<u8>>, SessionError> {
let layout = self.layout.as_ref().ok_or(SessionError::NotReady)?;
command.encode(layout).map_err(SessionError::Encode)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::change_frame::encode_property_changed;
use crate::Value;
#[test]
fn rejects_incremental_event_before_full_sync() {
let mut session = ProtocolSession::new();
let payload = encode_property_changed(&[], "property", &Value::Bool(true));
assert!(matches!(
session.ingest(&payload),
Err(SessionError::NotReady)
));
}
#[test]
fn structural_change_invalidates_session() {
let mut session = ProtocolSession::new();
let child_moved = [0x05, 0x00, 0x01, 0x00, 0x01, 0x01];
assert_eq!(
session.ingest(&child_moved).unwrap(),
SessionUpdate::NeedsFullSync
);
assert!(!session.is_ready());
}
}