use thiserror::Error;
use crate::envelope::{Cause, Code, ErrorForm, FormRefusal};
use crate::grammar::{KindToken, ZkKey, parse};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Form {
Mutation,
Delete,
Value,
Error,
Event,
Frame,
Heartbeat,
Snapshot,
}
impl Form {
pub const ALL: [Form; 8] = [
Form::Mutation,
Form::Delete,
Form::Value,
Form::Error,
Form::Event,
Form::Frame,
Form::Heartbeat,
Form::Snapshot,
];
#[must_use]
pub const fn code(self) -> u8 {
match self {
Form::Mutation => 0,
Form::Delete => 1,
Form::Value => 2,
Form::Error => 3,
Form::Event => 4,
Form::Frame => 5,
Form::Heartbeat => 6,
Form::Snapshot => 7,
}
}
#[must_use]
pub const fn from_code(code: u8) -> Option<Form> {
if code < 8 {
Some(Form::ALL[code as usize])
} else {
None
}
}
#[must_use]
pub const fn is_defined(self) -> bool {
true
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Form::Mutation => "mutation",
Form::Delete => "delete",
Form::Value => "value",
Form::Error => "error",
Form::Event => "event",
Form::Frame => "frame",
Form::Heartbeat => "heartbeat",
Form::Snapshot => "snapshot",
}
}
}
impl std::fmt::Display for Form {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SampleKind {
Put,
Delete,
Query,
Reply,
ReplyErr,
}
impl SampleKind {
pub const ALL: [SampleKind; 5] = [
SampleKind::Put,
SampleKind::Delete,
SampleKind::Query,
SampleKind::Reply,
SampleKind::ReplyErr,
];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
SampleKind::Put => "put",
SampleKind::Delete => "delete",
SampleKind::Query => "query",
SampleKind::Reply => "reply",
SampleKind::ReplyErr => "reply_err",
}
}
#[must_use]
pub const fn carries(self, form: Form) -> bool {
match self {
SampleKind::Put => matches!(
form,
Form::Mutation | Form::Event | Form::Frame | Form::Heartbeat | Form::Snapshot
),
SampleKind::Delete => matches!(form, Form::Delete),
SampleKind::Query | SampleKind::Reply => matches!(form, Form::Value),
SampleKind::ReplyErr => matches!(form, Form::Error),
}
}
}
impl std::fmt::Display for SampleKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Tag(u8);
impl Tag {
pub const NONE: Tag = Tag(0);
#[must_use]
pub const fn new(value: u8) -> Option<Tag> {
if value <= 0x0f {
Some(Tag(value))
} else {
None
}
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Header {
pub form: Form,
pub wide: bool,
pub tag: Tag,
}
impl Header {
#[must_use]
pub const fn from_byte(ch: u8) -> Header {
Header {
form: Form::ALL[(ch >> 5) as usize],
wide: ch & 0x10 != 0,
tag: Tag(ch & 0x0f),
}
}
#[must_use]
pub const fn byte(self) -> u8 {
(self.form.code() << 5) | ((self.wide as u8) << 4) | self.tag.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Run {
U16(u16),
U32(u32),
}
impl std::fmt::Display for Run {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Run::U16(v) => write!(f, "{v:04x}"),
Run::U32(v) => write!(f, "{v:08x}"),
}
}
}
impl Run {
#[must_use]
pub const fn is_wide(self) -> bool {
matches!(self, Run::U32(_))
}
#[must_use]
pub const fn value(self) -> u32 {
match self {
Run::U16(v) => v as u32,
Run::U32(v) => v,
}
}
#[must_use]
pub const fn width_bytes(self) -> usize {
if self.is_wide() { 4 } else { 2 }
}
#[must_use]
pub fn hex(self) -> String {
self.to_string()
}
#[must_use]
pub fn from_hex(text: &str) -> Option<Run> {
let lower_hex = text
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
if !lower_hex {
return None;
}
match text.len() {
4 => u16::from_str_radix(text, 16).ok().map(Run::U16),
8 => u32::from_str_radix(text, 16).ok().map(Run::U32),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub struct Seq(u32);
impl Seq {
pub const MAX: Seq = Seq(0x00ff_ffff);
#[must_use]
pub const fn new(value: u32) -> Option<Seq> {
if value <= Seq::MAX.0 {
Some(Seq(value))
} else {
None
}
}
#[must_use]
pub const fn get(self) -> u32 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Stamp {
pub run: Run,
pub seq: Seq,
}
impl Stamp {
#[must_use]
pub const fn envelope_bytes(self) -> usize {
1 + self.run.width_bytes() + 3
}
pub(crate) fn write_to(self, out: &mut Vec<u8>) {
match self.run {
Run::U16(v) => out.extend_from_slice(&v.to_be_bytes()),
Run::U32(v) => out.extend_from_slice(&v.to_be_bytes()),
}
out.extend_from_slice(&self.seq.0.to_be_bytes()[1..]);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum Refusal {
#[error("no byte, so no header byte")]
Empty,
#[error("the form {0} is reserved")]
Reserved(Form),
#[error("the form {form} on a {sample}, which does not carry it")]
WrongSample { form: Form, sample: SampleKind },
#[error("a {form} on a {kind} key, which does not carry it")]
KeyKind { form: Form, kind: KindToken },
#[error("a delete's tag is {}, not 0", .0.get())]
DeleteTag(Tag),
#[error("a request's width bit is 1, and a request carries no run")]
RequestRun,
#[error("an event's key ends in no occurrence chunk of a {} run", if *.wide { "32-bit" } else { "16-bit" })]
KeyStamp { wide: bool },
#[error("{have} bytes, short of the {need} that the header, the stamp and what follows need")]
Short { need: usize, have: usize },
#[error("{0} bytes after the form's end")]
Trailing(usize),
#[error("{}", cause_text(*.code, *.cause))]
Cause { code: Code, cause: Option<Cause> },
#[error("a detail on {0}, where only app carries one")]
Detail(Code),
#[error("the error's extension bit is set")]
Extension,
#[error("a message of {need} bytes, {have} given")]
MessageShort { need: usize, have: usize },
#[error("the message is not UTF-8")]
Utf8,
#[error("the event's time is an unused code")]
Time,
}
fn cause_text(code: Code, cause: Option<Cause>) -> String {
match cause {
None => format!("{code} without a cause"),
Some(c) => format!("a cause, {c}, on {code}"),
}
}
impl Refusal {
#[must_use]
pub const fn token(&self) -> &'static str {
match self {
Refusal::Empty | Refusal::Short { .. } | Refusal::MessageShort { .. } => "short",
Refusal::Reserved(_) => "form",
Refusal::WrongSample { .. } => "sample_kind",
Refusal::KeyKind { .. } => "key_kind",
Refusal::DeleteTag(_) => "tag",
Refusal::RequestRun => "request_run",
Refusal::KeyStamp { .. } => "key_stamp",
Refusal::Time => "time",
Refusal::Trailing(_) => "trailing",
Refusal::Cause { .. } => "cause",
Refusal::Detail(_) => "detail",
Refusal::Extension => "extension",
Refusal::Utf8 => "utf8",
}
}
}
fn read_header(
bytes: &[u8],
sample: SampleKind,
kind: Option<KindToken>,
) -> Result<(Header, &[u8]), Refusal> {
let (&ch, rest) = bytes.split_first().ok_or(Refusal::Empty)?;
let header = Header::from_byte(ch);
if !header.form.is_defined() {
return Err(Refusal::Reserved(header.form));
}
if !sample.carries(header.form) {
return Err(Refusal::WrongSample {
form: header.form,
sample,
});
}
if let Some(k) = kind
&& !key_carries(header.form, k)
{
return Err(Refusal::KeyKind {
form: header.form,
kind: k,
});
}
if header.form == Form::Delete && header.tag != Tag::NONE {
return Err(Refusal::DeleteTag(header.tag));
}
if sample == SampleKind::Query && header.wide {
return Err(Refusal::RequestRun);
}
Ok((header, rest))
}
const fn key_carries(form: Form, kind: KindToken) -> bool {
match form {
Form::Frame => matches!(kind, KindToken::Stream),
Form::Event => matches!(kind, KindToken::Events),
Form::Snapshot => matches!(kind, KindToken::State | KindToken::ExplicitState),
_ => true,
}
}
fn read(
bytes: &[u8],
sample: SampleKind,
kind: Option<KindToken>,
) -> Result<(Header, Stamp, &[u8]), Refusal> {
let (header, rest) = read_header(bytes, sample, kind)?;
let run_bytes = if header.wide { 4 } else { 2 };
let need = 1 + run_bytes + 3 + usize::from(header.form == Form::Error);
if bytes.len() < need {
return Err(Refusal::Short {
need,
have: bytes.len(),
});
}
let (run, rest) = rest.split_at(run_bytes);
let run = match *run {
[a, b] => Run::U16(u16::from_be_bytes([a, b])),
[a, b, c, d] => Run::U32(u32::from_be_bytes([a, b, c, d])),
_ => unreachable!("a run is 2 or 4 bytes"),
};
let (seq, rest) = rest.split_at(3);
let seq = Seq(u32::from_be_bytes([0, seq[0], seq[1], seq[2]]));
Ok((header, Stamp { run, seq }, rest))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Envelope<'a> {
pub form: Form,
pub tag: Tag,
pub stamp: Stamp,
pub record: &'a [u8],
}
impl<'a> Envelope<'a> {
#[must_use]
pub const fn mutation(tag: Tag, stamp: Stamp, record: &'a [u8]) -> Envelope<'a> {
Envelope {
form: Form::Mutation,
tag,
stamp,
record,
}
}
#[must_use]
pub const fn value(tag: Tag, stamp: Stamp, record: &'a [u8]) -> Envelope<'a> {
Envelope {
form: Form::Value,
tag,
stamp,
record,
}
}
#[must_use]
pub const fn frame(tag: Tag, stamp: Stamp, body: &'a [u8]) -> Envelope<'a> {
Envelope {
form: Form::Frame,
tag,
stamp,
record: body,
}
}
#[must_use]
pub const fn snapshot(tag: Tag, run: Run, asof: Seq, body: &'a [u8]) -> Envelope<'a> {
Envelope {
form: Form::Snapshot,
tag,
stamp: Stamp { run, seq: asof },
record: body,
}
}
#[must_use]
pub const fn is_frame(&self) -> bool {
matches!(self.form, Form::Frame)
}
#[must_use]
pub const fn is_heartbeat(&self) -> bool {
matches!(self.form, Form::Heartbeat)
}
#[must_use]
pub const fn is_snapshot(&self) -> bool {
matches!(self.form, Form::Snapshot)
}
pub fn parse(bytes: &'a [u8]) -> Result<Envelope<'a>, Refusal> {
Self::read_with(bytes, None)
}
pub fn parse_on(bytes: &'a [u8], kind: KindToken) -> Result<Envelope<'a>, Refusal> {
Self::read_with(bytes, Some(kind))
}
fn read_with(bytes: &'a [u8], kind: Option<KindToken>) -> Result<Envelope<'a>, Refusal> {
if let Some(&ch) = bytes.first() {
let header = Header::from_byte(ch);
if header.form == Form::Event {
read_header(bytes, SampleKind::Put, kind)?;
return Err(Refusal::KeyStamp { wide: header.wide });
}
}
let (header, stamp, record) = read(bytes, SampleKind::Put, kind)?;
Ok(Envelope {
form: header.form,
tag: header.tag,
stamp,
record,
})
}
#[must_use]
pub const fn header(&self) -> Header {
Header {
form: self.form,
wide: self.stamp.run.is_wide(),
tag: self.tag,
}
}
#[must_use]
pub fn write(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(self.stamp.envelope_bytes() + self.record.len());
out.push(self.header().byte());
self.stamp.write_to(&mut out);
out.extend_from_slice(self.record);
out
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DeleteStamp {
pub stamp: Stamp,
}
impl DeleteStamp {
pub fn parse(bytes: &[u8]) -> Result<DeleteStamp, Refusal> {
let (_, stamp, rest) = read(bytes, SampleKind::Delete, None)?;
if !rest.is_empty() {
return Err(Refusal::Trailing(rest.len()));
}
Ok(DeleteStamp { stamp })
}
#[must_use]
pub const fn header(&self) -> Header {
Header {
form: Form::Delete,
wide: self.stamp.run.is_wide(),
tag: Tag::NONE,
}
}
#[must_use]
pub fn write(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(self.stamp.envelope_bytes());
out.push(self.header().byte());
self.stamp.write_to(&mut out);
out
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Request<'a> {
pub tag: Tag,
pub record: &'a [u8],
}
impl<'a> Request<'a> {
#[must_use]
pub const fn new(tag: Tag, record: &'a [u8]) -> Request<'a> {
Request { tag, record }
}
#[must_use]
pub const fn header(&self) -> Header {
Header {
form: Form::Value,
wide: false,
tag: self.tag,
}
}
#[must_use]
pub fn write(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(1 + self.record.len());
out.push(self.header().byte());
out.extend_from_slice(self.record);
out
}
}
pub fn read_query(payload: &[u8]) -> Result<Request<'_>, Refusal> {
let (header, record) = read_header(payload, SampleKind::Query, None)?;
Ok(Request {
tag: header.tag,
record,
})
}
pub fn read_reply(payload: &[u8]) -> Result<Envelope<'_>, Refusal> {
let (header, stamp, record) = read(payload, SampleKind::Reply, None)?;
Ok(Envelope {
form: header.form,
tag: header.tag,
stamp,
record,
})
}
pub fn read_reply_err(payload: &[u8]) -> Result<ErrorForm<'_>, Refusal> {
let (header, stamp, rest) = read(payload, SampleKind::ReplyErr, None)?;
ErrorForm::after_stamp(header.tag, stamp, rest)
}
pub const ENCODING: &str = "zenoh/bytes";
pub fn read_value<'a>(encoding: &str, payload: &'a [u8]) -> Result<Envelope<'a>, FormRefusal> {
if encoding != ENCODING {
return Err(FormRefusal::Encoding(encoding.to_owned()));
}
read_reply(payload).map_err(FormRefusal::Form)
}
#[must_use]
pub fn enveloped_key(key: &str) -> bool {
enveloped_kind(key).is_some()
}
#[must_use]
pub fn enveloped_kind(key: &str) -> Option<KindToken> {
let mut rest = Some(key);
while let Some(k) = rest {
if k.starts_with("zk2/") {
match parse(k) {
Ok(ZkKey::Data { kind, .. }) => {
return (kind != KindToken::Op).then_some(kind);
}
Ok(_) => return None,
Err(_) => {}
}
}
rest = k.split_once('/').map(|(_, r)| r);
}
None
}
#[must_use]
pub fn carries(key: &str, encoding: &str) -> bool {
encoding == ENCODING && enveloped_key(key)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reading<'a> {
Plain,
Enveloped(Envelope<'a>),
Framed(Envelope<'a>),
Heartbeat(Envelope<'a>),
Event(Event<'a>),
Snapshot(Envelope<'a>),
Refused(Refusal),
}
#[must_use]
pub fn read_put<'a>(key: &str, encoding: &str, payload: &'a [u8]) -> Reading<'a> {
if !carries(key, encoding) {
return Reading::Plain;
}
if let Some(event) = read_event(key, payload) {
return match event {
Ok(e) => Reading::Event(e),
Err(r) => Reading::Refused(r),
};
}
let parsed = match enveloped_kind(key) {
Some(kind) => Envelope::parse_on(payload, kind),
None => Envelope::parse(payload),
};
match parsed {
Ok(e) if e.is_frame() => Reading::Framed(e),
Ok(e) if e.is_heartbeat() => Reading::Heartbeat(e),
Ok(e) if e.is_snapshot() => Reading::Snapshot(e),
Ok(e) => Reading::Enveloped(e),
Err(r) => Reading::Refused(r),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Event<'a> {
pub tag: Tag,
pub stamp: Stamp,
pub time: crate::collection::Time,
pub record: &'a [u8],
}
impl Event<'_> {
#[must_use]
pub const fn header(&self) -> Header {
Header {
form: Form::Event,
wide: self.stamp.run.is_wide(),
tag: self.tag,
}
}
#[must_use]
pub fn chunk(&self) -> String {
crate::chunk::write_occurrence(self.stamp)
}
#[must_use]
pub fn write(&self) -> Option<Vec<u8>> {
let (s, ms) = self.time.fields().ok()?;
let mut out = Vec::with_capacity(7 + self.record.len());
out.push(self.header().byte());
out.extend_from_slice(&s.to_be_bytes());
out.extend_from_slice(&ms.to_be_bytes());
out.extend_from_slice(self.record);
Some(out)
}
}
#[must_use]
pub fn read_event<'a>(key: &str, bytes: &'a [u8]) -> Option<Result<Event<'a>, Refusal>> {
let &ch = bytes.first()?;
if Header::from_byte(ch).form != Form::Event {
return None;
}
Some(event(key, bytes))
}
fn event<'a>(key: &str, bytes: &'a [u8]) -> Result<Event<'a>, Refusal> {
let (header, rest) = read_header(bytes, SampleKind::Put, enveloped_kind(key))?;
let stamp = key
.rsplit('/')
.next()
.and_then(crate::chunk::occurrence)
.filter(|s| s.run.is_wide() == header.wide)
.ok_or(Refusal::KeyStamp { wide: header.wide })?;
if rest.len() < 6 {
return Err(Refusal::Short {
need: 7,
have: bytes.len(),
});
}
let (t, record) = rest.split_at(6);
let time = crate::collection::Time::of_fields(
u32::from_be_bytes([t[0], t[1], t[2], t[3]]),
u16::from_be_bytes([t[4], t[5]]),
)
.map_err(|_| Refusal::Time)?;
Ok(Event {
tag: header.tag,
stamp,
time,
record,
})
}
#[must_use]
pub fn read_delete(key: &str, attachment: Option<&[u8]>) -> Option<Stamp> {
let a = attachment?;
if !enveloped_key(key) {
return None;
}
DeleteStamp::parse(a).ok().map(|d| d.stamp)
}
impl Refusal {
#[must_use]
pub fn reason(&self) -> String {
format!("zk2c envelope refused: {}", self.token())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_byte_is_a_header_and_writes_back() {
for ch in 0..=u8::MAX {
let h = Header::from_byte(ch);
assert_eq!(h.byte(), ch);
assert_eq!(h.form.code(), ch >> 5);
assert_eq!(Form::from_code(h.form.code()), Some(h.form));
}
assert_eq!(Form::from_code(8), None);
}
#[test]
fn the_worked_bytes() {
let h = Header::from_byte(0x1b);
assert_eq!((h.form, h.wide, h.tag.get()), (Form::Mutation, true, 11));
assert_eq!(Header::from_byte(0x20).form, Form::Delete);
assert!(!Header::from_byte(0x20).wide);
}
#[test]
fn bounds_by_construction() {
assert_eq!(Tag::new(15).map(Tag::get), Some(15));
assert_eq!(Tag::new(16), None);
assert_eq!(Seq::new(0x00ff_ffff), Some(Seq::MAX));
assert_eq!(Seq::new(0x0100_0000), None);
}
#[test]
fn sizes() {
let narrow = Stamp {
run: Run::U16(7),
seq: Seq::MAX,
};
let wide = Stamp {
run: Run::U32(7),
seq: Seq::MAX,
};
let record = [1, 2, 3];
for (stamp, over) in [(narrow, 6), (wide, 8)] {
let e = Envelope {
form: Form::Mutation,
tag: Tag::NONE,
stamp,
record: &record,
};
let bytes = e.write();
assert_eq!(bytes.len(), over + record.len());
assert_eq!(Envelope::parse(&bytes), Ok(e));
let d = DeleteStamp { stamp };
let bytes = d.write();
assert_eq!(bytes.len(), over);
assert_eq!(DeleteStamp::parse(&bytes), Ok(d));
}
}
#[test]
fn a_run_as_a_descriptor_states_it() {
assert_eq!(Run::U16(3).hex(), "0003");
assert_eq!(Run::U16(0xa1).hex(), "00a1");
assert_eq!(Run::U32(0xa1).hex(), "000000a1");
assert_eq!(Run::U32(u32::MAX).hex(), "ffffffff");
for r in [
Run::U16(0),
Run::U16(u16::MAX),
Run::U32(0),
Run::U32(0xdead_beef),
] {
assert_eq!(Run::from_hex(&r.hex()), Some(r));
}
assert_eq!(Run::from_hex("00a1"), Some(Run::U16(0xa1)));
assert_eq!(Run::from_hex("000000a1"), Some(Run::U32(0xa1)));
for bad in [
"",
"1a2b3",
"ABCD",
"00A1",
"abc",
"+0a1",
"-001",
"000000a1f",
" 0a1",
"g000",
] {
assert_eq!(Run::from_hex(bad), None, "{bad:?}");
}
}
#[test]
fn each_kind_refuses_the_others_form() {
let d = DeleteStamp {
stamp: Stamp {
run: Run::U16(1),
seq: Seq::default(),
},
}
.write();
assert_eq!(
Envelope::parse(&d),
Err(Refusal::WrongSample {
form: Form::Delete,
sample: SampleKind::Put
})
);
let m = Envelope {
form: Form::Mutation,
tag: Tag::NONE,
stamp: Stamp {
run: Run::U16(1),
seq: Seq::default(),
},
record: &[],
}
.write();
assert_eq!(
DeleteStamp::parse(&m).map_err(|r| r.token()),
Err("sample_kind")
);
}
#[test]
fn a_sample_carries_an_envelope_by_its_key_kind_and_its_encoding() {
for key in [
"zk2/h/s/i.v1/stream/pose",
"zk2/h/s/i.v1/@stream/frames/f1",
"zk2/h/s/i.v1/state/mode",
"zk2/h/s/i.v1/@state/tracks/t1",
"zk2/h/s/i.v1/events/fault/002g0009",
"prod/zk2/h/s/i.v1/state/mode",
"site/a/zk2/h/s/i.v1/stream/pose",
"zk2/zk2/h/s/i.v1/state/mode",
] {
assert!(enveloped_key(key), "{key}");
assert!(enveloped_kind(key).is_some(), "{key}");
assert!(carries(key, ENCODING), "{key}");
for other in [
"application/json",
"application/cbor",
"application/protobuf",
"zenoh/bytes;x",
"image/x-portable-anymap",
"",
] {
assert!(!carries(key, other), "{key} under {other:?}");
}
}
for key in [
"zk2/h/s/i.v1/@op/reset",
"zk2/h/s/@zk/instance/0a1b2c3d4e5f6071",
"zk2/@zk/contract/i.v1/0000000000000000000000000000000000000000000000000000000000000000",
"demo/tick",
"seedtest/state/health",
"zk2/h/s/i.v1",
"zk2",
"",
] {
assert!(!enveloped_key(key), "{key}");
assert_eq!(enveloped_kind(key), None, "{key}");
assert!(!carries(key, ENCODING), "{key}");
}
assert_eq!(
enveloped_kind("prod/zk2/h/s/i.v1/@stream/frames/f1"),
Some(KindToken::ExplicitStream)
);
assert_eq!(
enveloped_kind("zk2/h/s/i.v1/events/fault/002g0009"),
Some(KindToken::Events)
);
assert_eq!(
enveloped_kind("zk2/h/s/i.v1/events/fault/01arz3ndektsv4rrffq69g5fav"),
None,
"a ULID's key is no zk2 key (core 0.103 §1.2)"
);
}
#[test]
fn a_put_reads_plain_enveloped_or_refused() {
let key = "zk2/h/s/i.v1/state/mode";
let stamp = Stamp {
run: Run::U16(7),
seq: Seq::new(3).unwrap(),
};
let bytes = Envelope {
form: Form::Mutation,
tag: Tag::NONE,
stamp,
record: br#"{"up":true}"#,
}
.write();
assert_eq!(read_put(key, "application/json", &bytes), Reading::Plain);
let Reading::Enveloped(e) = read_put(key, ENCODING, &bytes) else {
panic!("an envelope")
};
assert_eq!((e.stamp, e.record), (stamp, &br#"{"up":true}"#[..]));
let refused = read_put(key, ENCODING, br#"{"up":true}"#);
assert_eq!(
refused,
Reading::Refused(Refusal::WrongSample {
form: Form::Error,
sample: SampleKind::Put
})
);
let Reading::Refused(r) = refused else {
unreachable!()
};
assert_eq!(r.reason(), "zk2c envelope refused: sample_kind");
assert_eq!(
read_put(key, ENCODING, &[]),
Reading::Refused(Refusal::Empty)
);
assert_eq!(read_put("demo/tick", ENCODING, &bytes), Reading::Plain);
}
#[test]
fn a_delete_carries_its_stamp_in_its_attachment_or_none() {
let key = "zk2/h/s/i.v1/state/mode";
let stamp = Stamp {
run: Run::U32(0xdead_beef),
seq: Seq::new(9).unwrap(),
};
let att = DeleteStamp { stamp }.write();
assert_eq!(read_delete(key, Some(&att)), Some(stamp));
assert_eq!(read_delete(key, None), None);
assert_eq!(read_delete(key, Some(br#"{"confirmed":true}"#)), None);
assert_eq!(read_delete(key, Some(&[0x00, 0, 7, 0, 0, 9])), None);
assert_eq!(read_delete("demo/tick", Some(&att)), None);
assert_eq!(read_delete("zk2/h/s/i.v1/@op/reset", Some(&att)), None);
}
#[test]
fn a_reply_is_a_value_form_under_zenoh_bytes_alone() {
let stamp = Stamp {
run: Run::U16(1),
seq: Seq::new(7).unwrap(),
};
let bytes = Envelope::value(Tag::NONE, stamp, br#"{"up":true}"#).write();
let v = read_value(ENCODING, &bytes).expect("a value");
assert_eq!(
(v.form, v.stamp, v.record),
(Form::Value, stamp, &br#"{"up":true}"#[..])
);
assert_eq!(
read_value(ENCODING, br#"{"up":true}"#),
Err(FormRefusal::Form(Refusal::WrongSample {
form: Form::Error,
sample: SampleKind::Reply
}))
);
for other in ["application/json", "zenoh/bytes;x", "zenoh/string"] {
let r = read_value(other, &bytes);
assert_eq!(r, Err(FormRefusal::Encoding(other.to_owned())), "{other}");
assert_eq!(r.unwrap_err().token(), "encoding");
}
}
}