Skip to main content

spoolframe_protocol/
features.rs

1//! Regular features: how a server knows a client handles something.
2//!
3//! A client names the features it handles in [`Hello::features`]; the
4//! server's answer, [`ServerInfo::features`], names those of them it has.
5//! A feature is on for the connection only when both named it. Then, and
6//! only then, the server answers the feature's requests (a request of a
7//! feature that is off is `Unsupported`, as one it does not know) and
8//! sends its events. A name either side does not know is ignored, never
9//! an error, and both fields are left out when empty, so an older peer
10//! sends and reads what it did before.
11//!
12//! Every opt-in request and event comes with a feature. A new reply field
13//! needs none: it is `serde(default)`, and an `Option` where its absence
14//! means something else than its default. Nothing is decided from a
15//! version number. Unlike the experimental features
16//! ([`crate::experimental`]), these are ordinary protocol, with its
17//! stability, and a server that has one always names it when asked.
18//!
19//! The scheme is dated: a feature is what was added by its date, whatever
20//! the mix, so a client names one thing for all of it. Later additions get
21//! a new dated name; the one a release has shipped never changes what it
22//! holds, and a name stays once added.
23//!
24//! [`Hello::features`]: crate::Hello::features
25//! [`ServerInfo::features`]: crate::ServerInfo::features
26
27use std::fmt;
28
29use enumset::{EnumSet, EnumSetType};
30
31/// A regular feature. On the wire it is its name ([`Feature::name`]).
32#[derive(Debug, Hash, PartialOrd, Ord, EnumSetType)]
33#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
34#[non_exhaustive]
35pub enum Feature {
36    /// `spoolframe:october-2026`: `ProfileRemoved`, `PinChanged` and
37    /// `WatchChanged` on the events stream, `NextEpisode`, `ShowNext`, and
38    /// `BeginInvitePasskey` and `RedeemInviteWithPasskey`, an account made
39    /// with an invite and an app passkey.
40    October2026,
41}
42
43/// A set of features: [`Features::all`] is every one this build knows,
44/// and `client & server` those on for a connection. Bit positions are
45/// this build's own; only names cross the wire ([`names`]).
46pub type Features = EnumSet<Feature>;
47
48impl Feature {
49    /// Its name on the wire: the one place the names are written.
50    pub const fn name(self) -> &'static str {
51        match self {
52            Feature::October2026 => "spoolframe:october-2026",
53        }
54    }
55
56    /// The feature named `name`, if this build knows it.
57    pub fn of(name: &str) -> Option<Feature> {
58        Features::all().iter().find(|f| f.name() == name)
59    }
60}
61
62impl fmt::Display for Feature {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str(self.name())
65    }
66}
67
68/// [`Features`] on the wire, for `#[serde(with = "names")]`: the list
69/// of their names. A name this build does not know is skipped as it is
70/// read. Never enumset's own serde, which would send its bits.
71pub mod names {
72    use std::fmt;
73
74    use serde::de::{SeqAccess, Visitor};
75    use serde::ser::SerializeSeq;
76    use serde::{Deserializer, Serializer};
77
78    use super::{Feature, Features};
79
80    pub fn serialize<S: Serializer>(features: &Features, s: S) -> Result<S::Ok, S::Error> {
81        let mut names = s.serialize_seq(Some(features.len()))?;
82        for feature in features.iter() {
83            names.serialize_element(feature.name())?;
84        }
85        names.end()
86    }
87
88    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Features, D::Error> {
89        struct Names;
90
91        impl<'de> Visitor<'de> for Names {
92            type Value = Features;
93
94            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95                f.write_str("a list of feature names")
96            }
97
98            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Features, A::Error> {
99                let mut features = Features::empty();
100                // Owned: CBOR text may come in chunks.
101                while let Some(name) = seq.next_element::<String>()? {
102                    if let Some(feature) = Feature::of(&name) {
103                        features |= feature;
104                    }
105                }
106                Ok(features)
107            }
108        }
109
110        d.deserialize_seq(Names)
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use serde::{Deserialize, Serialize};
117
118    use super::*;
119
120    /// A field as `Hello` and `ServerInfo` carry it.
121    #[derive(Debug, PartialEq, Serialize, Deserialize)]
122    struct Named(#[serde(with = "names")] Features);
123
124    #[test]
125    fn every_feature_is_named_once_and_read_back() {
126        let mut names: Vec<&str> = Features::all().iter().map(Feature::name).collect();
127        for feature in Features::all() {
128            assert_eq!(Feature::of(feature.name()), Some(feature));
129            assert!(feature.name().starts_with("spoolframe:"), "{feature}");
130        }
131        names.sort_unstable();
132        names.dedup();
133        assert_eq!(names.len(), Features::all().len());
134        assert_eq!(Feature::of("spoolframe:teleport"), None);
135    }
136
137    /// What is on for a connection: those both sides named.
138    #[test]
139    fn on_is_what_both_named() {
140        let both = Features::only(Feature::October2026);
141        assert_eq!(both & both, both);
142        assert!((both & Features::empty()).is_empty());
143    }
144
145    /// Only names cross the wire, in JSON and in CBOR.
146    #[test]
147    fn a_set_goes_as_the_list_of_its_names() {
148        let set = Named(Feature::October2026.into());
149        assert_eq!(
150            serde_json::to_value(&set).unwrap(),
151            serde_json::json!(["spoolframe:october-2026"])
152        );
153        let cbor = crate::codec::encode(&set).unwrap();
154        let value: ciborium::Value = ciborium::from_reader(cbor.as_slice()).unwrap();
155        assert_eq!(
156            value,
157            ciborium::Value::Array(vec!["spoolframe:october-2026".into()])
158        );
159        assert_eq!(crate::codec::decode::<Named>(&cbor).unwrap(), set);
160    }
161
162    /// A name this build does not know is skipped; the rest are read.
163    #[test]
164    fn an_unknown_name_is_skipped() {
165        let names = vec!["spoolframe:teleport", "spoolframe:october-2026"];
166        let read: Named = serde_json::from_value(serde_json::json!(names)).unwrap();
167        assert_eq!(read, Named(Feature::October2026.into()));
168        let cbor = crate::codec::encode(&names).unwrap();
169        assert_eq!(
170            crate::codec::decode::<Named>(&cbor).unwrap(),
171            Named(Feature::October2026.into())
172        );
173    }
174}