Skip to main content

weirdnet_service/
protocol.rs

1//! Versioned protocol ids.
2
3use std::fmt;
4use std::str::FromStr;
5
6use crate::ServiceError;
7
8/// The envelope version of this crate's messages (`Hello`, `Subscribe` and the frames around
9/// bodies). Independent of an application's [`ProtocolId`] version.
10pub const WIRE: u8 = 1;
11
12/// A protocol id with a version: `/myapp/api/2` is base `/myapp/api`, version 2.
13///
14/// Bump the version when a protocol's messages change incompatibly; serve the old and new
15/// versions side by side for a while, and let clients try the newest first
16/// ([`Client::session_any`](crate::Client::session_any)).
17#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct ProtocolId {
19    base: String,
20    version: u32,
21    id: String,
22}
23
24impl ProtocolId {
25    /// `base` starts with `/`, has non-empty segments of `a-z A-Z 0-9 . _ -`, and does not end
26    /// with `/`; `version` is 1 or more.
27    pub fn new(base: &str, version: u32) -> Result<Self, ServiceError> {
28        let ok_segment = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'));
29        let Some(rest) = base.strip_prefix('/') else {
30            return Err(ServiceError::bad_request(format!("protocol base {base:?} must start with /")));
31        };
32        if !rest.split('/').all(ok_segment) || base.len() > 200 {
33            return Err(ServiceError::bad_request(format!("protocol base {base:?} is not valid")));
34        }
35        if version == 0 {
36            return Err(ServiceError::bad_request("protocol versions start at 1"));
37        }
38        Ok(Self { base: base.to_string(), version, id: format!("{base}/{version}") })
39    }
40
41    /// Parses `/base/N`.
42    pub fn parse(id: &str) -> Result<Self, ServiceError> {
43        let (base, v) = id.rsplit_once('/').ok_or_else(|| ServiceError::bad_request(format!("{id:?} is not a protocol id")))?;
44        if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) || v.starts_with('0') {
45            return Err(ServiceError::bad_request(format!("{id:?} does not end in a version")));
46        }
47        let version = v.parse().map_err(|_| ServiceError::bad_request(format!("{id:?}: version too large")))?;
48        Self::new(base, version)
49    }
50
51    pub fn base(&self) -> &str {
52        &self.base
53    }
54
55    pub fn version(&self) -> u32 {
56        self.version
57    }
58
59    /// The full id, as streams are opened with it.
60    pub fn as_str(&self) -> &str {
61        &self.id
62    }
63
64    /// The same base at another version.
65    pub fn with_version(&self, version: u32) -> Result<Self, ServiceError> {
66        Self::new(&self.base, version)
67    }
68}
69
70impl fmt::Display for ProtocolId {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        f.write_str(&self.id)
73    }
74}
75
76impl FromStr for ProtocolId {
77    type Err = ServiceError;
78
79    fn from_str(s: &str) -> Result<Self, Self::Err> {
80        Self::parse(s)
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn ids_parse_print_and_validate() {
90        let p = ProtocolId::new("/myapp/api", 2).unwrap();
91        assert_eq!((p.as_str(), p.base(), p.version()), ("/myapp/api/2", "/myapp/api", 2));
92        assert_eq!(ProtocolId::parse("/myapp/api/2").unwrap(), p);
93        assert_eq!(p.with_version(1).unwrap().to_string(), "/myapp/api/1");
94        for bad in ["myapp/api/1", "/myapp//api/1", "/myapp/api/", "/myapp/api/0", "/myapp/api/v1", "/my app/1", "/myapp/api/01"] {
95            assert!(ProtocolId::parse(bad).is_err(), "{bad}");
96        }
97        assert!(ProtocolId::new("/x", 0).is_err());
98        assert!(ProtocolId::parse("/x/1").unwrap() < ProtocolId::parse("/x/2").unwrap());
99    }
100}