Skip to main content

weirdnet_streaming/
wire.rs

1//! The wire format: length-prefixed messages on one weirdnet-net stream.
2//!
3//! Each message is a big-endian `u32` length, then a type byte, then the body. The subscriber
4//! sends one [`Msg::Hello`]; the publisher answers [`Msg::Info`] or [`Msg::Refused`], then
5//! frames, info changes and finally [`Msg::Ended`].
6use crate::types::{Frame, StreamId, StreamInfo, SubscribeOptions};
7use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
8use serde::{Deserialize, Serialize};
9use std::io;
10
11/// The largest message accepted (16 MiB).
12pub const MAX_MESSAGE: usize = 16 << 20;
13
14/// What the subscriber asks for.
15#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
16pub struct Hello {
17    /// The stream.
18    pub stream: StreamId,
19    /// Where to start and how much the publisher may queue for this subscriber.
20    pub options: SubscribeOptions,
21}
22
23/// One message.
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub enum Msg {
26    /// Subscriber to publisher: the request.
27    Hello(Hello),
28    /// The stream's info (first answer, and on change).
29    Info(StreamInfo),
30    /// A frame.
31    Frame(Frame),
32    /// The stream is over.
33    Ended,
34    /// The subscription is refused, with a reason.
35    Refused(String),
36}
37
38const HELLO: u8 = 1;
39const INFO: u8 = 2;
40const FRAME: u8 = 3;
41const ENDED: u8 = 4;
42const REFUSED: u8 = 5;
43
44fn bad(what: &str) -> io::Error {
45    io::Error::new(io::ErrorKind::InvalidData, what.to_string())
46}
47
48impl Msg {
49    /// The bytes of this message, length prefix included.
50    pub fn encode(&self) -> Vec<u8> {
51        let mut body = Vec::new();
52        match self {
53            Msg::Hello(h) => {
54                body.push(HELLO);
55                body.extend(serde_json::to_vec(h).expect("hello serializes"));
56            }
57            Msg::Info(i) => {
58                body.push(INFO);
59                body.extend(serde_json::to_vec(i).expect("info serializes"));
60            }
61            Msg::Frame(f) => {
62                body.push(FRAME);
63                body.extend(f.seq.to_be_bytes());
64                body.extend(f.pts.to_be_bytes());
65                body.extend(f.duration.to_be_bytes());
66                body.push(u8::from(f.key) | if f.meta.is_some() { 2 } else { 0 });
67                if let Some(m) = &f.meta {
68                    body.extend((m.len() as u32).to_be_bytes());
69                    body.extend(m);
70                }
71                body.extend(&f.payload);
72            }
73            Msg::Ended => body.push(ENDED),
74            Msg::Refused(r) => {
75                body.push(REFUSED);
76                body.extend(r.as_bytes());
77            }
78        }
79        let mut out = (body.len() as u32).to_be_bytes().to_vec();
80        out.extend(body);
81        out
82    }
83
84    /// Parse a message body (without the length prefix).
85    pub fn decode(body: &[u8]) -> io::Result<Msg> {
86        let (&t, rest) = body.split_first().ok_or_else(|| bad("empty message"))?;
87        Ok(match t {
88            HELLO => Msg::Hello(serde_json::from_slice(rest).map_err(|_| bad("hello"))?),
89            INFO => Msg::Info(serde_json::from_slice(rest).map_err(|_| bad("info"))?),
90            FRAME => {
91                if rest.len() < 21 {
92                    return Err(bad("short frame"));
93                }
94                let seq = u64::from_be_bytes(rest[0..8].try_into().expect("8 bytes"));
95                let pts = u64::from_be_bytes(rest[8..16].try_into().expect("8 bytes"));
96                let duration = u32::from_be_bytes(rest[16..20].try_into().expect("4 bytes"));
97                let flags = rest[20];
98                let mut p = &rest[21..];
99                let meta = if flags & 2 != 0 {
100                    if p.len() < 4 {
101                        return Err(bad("short frame meta"));
102                    }
103                    let n = u32::from_be_bytes(p[0..4].try_into().expect("4 bytes")) as usize;
104                    let m = p.get(4..4 + n).ok_or_else(|| bad("short frame meta"))?.to_vec();
105                    p = &p[4 + n..];
106                    Some(m)
107                } else {
108                    None
109                };
110                Msg::Frame(Frame { seq, pts, duration, key: flags & 1 != 0, payload: p.to_vec(), meta })
111            }
112            ENDED => Msg::Ended,
113            REFUSED => Msg::Refused(String::from_utf8_lossy(rest).into_owned()),
114            _ => return Err(bad("unknown message type")),
115        })
116    }
117}
118
119/// Write one message.
120pub async fn write<W: AsyncWrite + Unpin>(w: &mut W, m: &Msg) -> io::Result<()> {
121    w.write_all(&m.encode()).await?;
122    w.flush().await
123}
124
125/// Read one message; `Ok(None)` at a clean end of stream.
126pub async fn read<R: AsyncRead + Unpin>(r: &mut R) -> io::Result<Option<Msg>> {
127    let mut len = [0u8; 4];
128    match r.read_exact(&mut len).await {
129        Ok(()) => {}
130        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
131        Err(e) => return Err(e),
132    }
133    let n = u32::from_be_bytes(len) as usize;
134    if n == 0 || n > MAX_MESSAGE {
135        return Err(bad("bad message length"));
136    }
137    let mut body = vec![0u8; n];
138    r.read_exact(&mut body).await?;
139    Msg::decode(&body).map(Some)
140}