use crate::frame::Frame;
pub const LENGTH_PREFIX_BYTES: usize = 4;
pub(crate) const INCONSISTENT_SCOPE_ERROR_PREFIX: &str = "error frame violates the id/scope rule: ";
pub const DEFAULT_MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum CodecError {
#[error("truncated length prefix: got {available} of {LENGTH_PREFIX_BYTES} bytes")]
TruncatedLengthPrefix { available: usize },
#[error("truncated payload: declared {declared} bytes, got {available}")]
TruncatedPayload { declared: usize, available: usize },
#[error("frame of {declared} bytes exceeds the {max} byte maximum")]
FrameTooLarge { declared: usize, max: usize },
#[error("frame of {declared} bytes exceeds the u32 length prefix's {max} byte capacity")]
U32PrefixLimitExceeded { declared: usize, max: usize },
#[error("payload is not valid JSON: {0}")]
InvalidJson(String),
#[error("payload has no string \"kind\" discriminant field")]
MissingKind,
#[error("unknown frame kind: {0:?}")]
UnknownFrameKind(String),
#[error("frame kind {kind:?}: {detail}")]
InvalidFields { kind: String, detail: String },
#[error("error frame violates the id/scope rule: {detail}")]
InconsistentErrorScope { detail: String },
#[error(
"fallback error frame (unrecognized code {code:?}) is not re-encodable: \
re-encoding would emit \"internal\" and discard the newer wire code"
)]
FallbackFrameNotEncodable { code: String },
}
impl CodecError {
pub const fn wire_code(&self) -> crate::error::WireErrorCode {
match self {
CodecError::FrameTooLarge { .. } | CodecError::U32PrefixLimitExceeded { .. } => {
crate::error::WireErrorCode::FrameTooLarge
}
CodecError::TruncatedLengthPrefix { .. }
| CodecError::TruncatedPayload { .. }
| CodecError::InvalidJson(_)
| CodecError::MissingKind
| CodecError::UnknownFrameKind(_)
| CodecError::InvalidFields { .. }
| CodecError::InconsistentErrorScope { .. } => {
crate::error::WireErrorCode::MalformedFrame
}
CodecError::FallbackFrameNotEncodable { .. } => crate::error::WireErrorCode::Internal,
}
}
}
impl From<&CodecError> for crate::error::WireErrorCode {
fn from(err: &CodecError) -> Self {
err.wire_code()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameCodec {
max_frame_bytes: usize,
}
impl FrameCodec {
pub const fn new(max_frame_bytes: usize) -> Self {
Self { max_frame_bytes }
}
pub const fn max_frame_bytes(&self) -> usize {
self.max_frame_bytes
}
pub fn encode(&self, frame: &Frame) -> Result<Vec<u8>, CodecError> {
encode_frame_with_max(frame, self.max_frame_bytes)
}
pub fn decode(&self, buf: &[u8]) -> Result<Frame, CodecError> {
decode_frame(buf, self.max_frame_bytes)
}
pub fn decode_with_consumed(&self, buf: &[u8]) -> Result<(Frame, usize), CodecError> {
decode_frame_with_consumed(buf, self.max_frame_bytes)
}
}
impl Default for FrameCodec {
fn default() -> Self {
Self::new(DEFAULT_MAX_FRAME_BYTES)
}
}
pub fn encode_frame(frame: &Frame) -> Result<Vec<u8>, CodecError> {
encode_frame_with_max(frame, DEFAULT_MAX_FRAME_BYTES)
}
pub fn encode_frame_with_max(frame: &Frame, max_frame_bytes: usize) -> Result<Vec<u8>, CodecError> {
validate_frame_for_wire(frame)?;
let payload = serde_json::to_vec(frame).map_err(|e| CodecError::InvalidJson(e.to_string()))?;
check_encode_payload_len(payload.len(), max_frame_bytes)?;
let mut buf = Vec::with_capacity(LENGTH_PREFIX_BYTES + payload.len());
buf.extend_from_slice(&(payload.len() as u32).to_be_bytes());
buf.extend_from_slice(&payload);
Ok(buf)
}
fn validate_frame_for_wire(frame: &Frame) -> Result<(), CodecError> {
use crate::error::TerminalScope;
fn check_id(kind: &str, id: &crate::frame::OperationId) -> Result<(), CodecError> {
if id.0.is_empty() {
return Err(CodecError::InvalidFields {
kind: kind.to_string(),
detail: "operation id must be a non-empty string".to_string(),
});
}
Ok(())
}
match frame {
Frame::Handshake { version } => {
if version.get() == 0 {
return Err(CodecError::InvalidFields {
kind: "handshake".to_string(),
detail: "protocol version 0 does not exist".to_string(),
});
}
}
Frame::HandshakeAck { version } => {
if version.get() == 0 {
return Err(CodecError::InvalidFields {
kind: "handshake_ack".to_string(),
detail: "protocol version 0 does not exist".to_string(),
});
}
}
Frame::Event { .. } => {}
Frame::Request { id, .. } => check_id("request", id)?,
Frame::Response { id, .. } => check_id("response", id)?,
Frame::Cancel { id } => check_id("cancel", id)?,
Frame::Subscribe { id, .. } => check_id("subscribe", id)?,
Frame::SubscribeAck { id, .. } => check_id("subscribe_ack", id)?,
Frame::Unsubscribe { id, .. } => check_id("unsubscribe", id)?,
Frame::UnsubscribeAck { id, .. } => check_id("unsubscribe_ack", id)?,
Frame::Error {
id,
code,
unrecognized_code,
..
} => {
if let Some(raw_code) = unrecognized_code {
return Err(CodecError::FallbackFrameNotEncodable {
code: raw_code.clone(),
});
}
if let Some(id) = id {
check_id("error", id)?;
}
match (code.terminal_scope(), id) {
(TerminalScope::Connection, Some(id)) => {
return Err(CodecError::InconsistentErrorScope {
detail: format!(
"connection-terminal code {code} must not carry an operation id, got {id}"
),
});
}
(TerminalScope::Request, None) => {
return Err(CodecError::InconsistentErrorScope {
detail: format!(
"request-terminal code {code} must echo the operation id it terminates"
),
});
}
(TerminalScope::Connection, None) | (TerminalScope::Request, Some(_)) => {}
}
}
}
Ok(())
}
fn check_encode_payload_len(payload_len: usize, max_frame_bytes: usize) -> Result<(), CodecError> {
if payload_len > max_frame_bytes {
return Err(CodecError::FrameTooLarge {
declared: payload_len,
max: max_frame_bytes,
});
}
if payload_len > u32::MAX as usize {
return Err(CodecError::U32PrefixLimitExceeded {
declared: payload_len,
max: u32::MAX as usize,
});
}
Ok(())
}
pub fn decode_frame(buf: &[u8], max_frame_bytes: usize) -> Result<Frame, CodecError> {
decode_frame_with_consumed(buf, max_frame_bytes).map(|(frame, _)| frame)
}
pub fn decode_frame_with_consumed(
buf: &[u8],
max_frame_bytes: usize,
) -> Result<(Frame, usize), CodecError> {
if buf.len() < LENGTH_PREFIX_BYTES {
return Err(CodecError::TruncatedLengthPrefix {
available: buf.len(),
});
}
let mut len_bytes = [0u8; LENGTH_PREFIX_BYTES];
len_bytes.copy_from_slice(&buf[..LENGTH_PREFIX_BYTES]);
let declared = u32::from_be_bytes(len_bytes) as usize;
if declared > max_frame_bytes {
return Err(CodecError::FrameTooLarge {
declared,
max: max_frame_bytes,
});
}
let available = buf.len() - LENGTH_PREFIX_BYTES;
if available < declared {
return Err(CodecError::TruncatedPayload {
declared,
available,
});
}
let payload = &buf[LENGTH_PREFIX_BYTES..LENGTH_PREFIX_BYTES + declared];
let frame = decode_payload(payload)?;
Ok((frame, LENGTH_PREFIX_BYTES + declared))
}
pub(crate) fn decode_payload(payload: &[u8]) -> Result<Frame, CodecError> {
let value: serde_json::Value =
serde_json::from_slice(payload).map_err(|e| CodecError::InvalidJson(e.to_string()))?;
let kind = value
.as_object()
.and_then(|obj| obj.get("kind"))
.and_then(|k| k.as_str())
.ok_or(CodecError::MissingKind)?
.to_string();
if !crate::frame::FRAME_KINDS.contains(&kind.as_str()) {
return Err(CodecError::UnknownFrameKind(kind));
}
serde_json::from_value(value).map_err(|e| {
let detail = e.to_string();
match detail.strip_prefix(INCONSISTENT_SCOPE_ERROR_PREFIX) {
Some(scope_detail) => CodecError::InconsistentErrorScope {
detail: scope_detail.to_string(),
},
None => CodecError::InvalidFields { kind, detail },
}
})
}
#[cfg(test)]
#[path = "codec_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "codec_configured_max_tests.rs"]
mod configured_max_tests;