use bytes::Bytes;
use crate::decode::{Body, Decoder};
use crate::handler::Handler;
use crate::session::Session;
pub(crate) enum Data<'a> {
Text(&'a str, Option<&'a Bytes>),
Binary(&'a Bytes),
}
pub(crate) fn on_data<H: Handler>(
decoder: &mut Decoder,
session: &mut Session<H>,
data: Data<'_>,
) -> bool {
if session.sealing.is_some() {
return on_session_data(session, data);
}
match data {
Data::Text(text, frame) => {
let _ = session.on_json(text, frame);
}
Data::Binary(data) => {
let prefixed = matches!(data.as_ref(), [b'C' | b'M' | b'E', b':', ..]);
let understood = match decoder.binary(data) {
Ok(Body::Json(json)) => session.on_json(json, Some(data)),
Ok(Body::Msgpack(bytes)) => session.on_msgpack(bytes, Some(data)),
Ok(Body::Sealed) => {
tracing::warn!("[WSE] sealed frame without an end-to-end session dropped");
true
}
Ok(Body::Binary) => false,
Err(e) if prefixed => {
tracing::warn!("[WSE] frame of {} bytes dropped: {e}", data.len());
true
}
Err(_) => false,
};
if !understood && !prefixed {
session.handler.binary(data);
}
}
}
true
}
fn on_session_data<H: Handler>(session: &mut Session<H>, data: Data<'_>) -> bool {
match data {
Data::Binary(data) if data.starts_with(b"E:") => {
let Some(sealing) = session.sealing.as_mut() else {
return false;
};
match sealing.open(data) {
Ok(Some(plain)) => {
let plain = Bytes::from(plain);
let understood = match plain.strip_prefix(b"M:") {
Some(msgpack) => session.on_msgpack(msgpack, Some(&plain)),
None => std::str::from_utf8(&plain)
.ok()
.filter(|text| text.trim_start().starts_with('{'))
.is_some_and(|text| session.on_json(text, Some(&plain))),
};
if !understood {
session.handler.binary(&plain);
}
true
}
Ok(None) => true,
Err(error) => {
session.fail(error);
false
}
}
}
Data::Text(text, _) => {
session.on_unsealed(Some(text));
false
}
Data::Binary(data) => {
session.on_unsealed(std::str::from_utf8(data).ok());
false
}
}
}