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. A
18//! name stays once added.
19//!
20//! [`Hello::features`]: crate::Hello::features
21//! [`ServerInfo::features`]: crate::ServerInfo::features
22
23use std::fmt;
24
25use enumset::{EnumSet, EnumSetType};
26
27/// A regular feature. On the wire it is its name ([`Feature::name`]).
28#[derive(Debug, Hash, PartialOrd, Ord, EnumSetType)]
29#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
30#[non_exhaustive]
31pub enum Feature {
32    /// `ProfileRemoved` and `PinChanged` on the events stream.
33    ProfileEvents,
34    /// `WatchChanged` on the events stream.
35    WatchEvents,
36    /// `NextEpisode` and `ShowNext`.
37    NextEpisodes,
38    /// `BeginInvitePasskey` and `RedeemInviteWithPasskey`: an account
39    /// made with an invite and an app passkey.
40    InvitePasskeys,
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::ProfileEvents => "spoolframe:profile-events",
53            Feature::WatchEvents => "spoolframe:watch-events",
54            Feature::NextEpisodes => "spoolframe:next-episode",
55            Feature::InvitePasskeys => "spoolframe:invite-passkeys",
56        }
57    }
58
59    /// The feature named `name`, if this build knows it.
60    pub fn of(name: &str) -> Option<Feature> {
61        Features::all().iter().find(|f| f.name() == name)
62    }
63}
64
65impl fmt::Display for Feature {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(self.name())
68    }
69}
70
71/// [`Features`] on the wire, for `#[serde(with = "names")]`: the list
72/// of their names. A name this build does not know is skipped as it is
73/// read. Never enumset's own serde, which would send its bits.
74pub mod names {
75    use std::fmt;
76
77    use serde::de::{SeqAccess, Visitor};
78    use serde::ser::SerializeSeq;
79    use serde::{Deserializer, Serializer};
80
81    use super::{Feature, Features};
82
83    pub fn serialize<S: Serializer>(features: &Features, s: S) -> Result<S::Ok, S::Error> {
84        let mut names = s.serialize_seq(Some(features.len()))?;
85        for feature in features.iter() {
86            names.serialize_element(feature.name())?;
87        }
88        names.end()
89    }
90
91    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Features, D::Error> {
92        struct Names;
93
94        impl<'de> Visitor<'de> for Names {
95            type Value = Features;
96
97            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98                f.write_str("a list of feature names")
99            }
100
101            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Features, A::Error> {
102                let mut features = Features::empty();
103                // Owned: CBOR text may come in chunks.
104                while let Some(name) = seq.next_element::<String>()? {
105                    if let Some(feature) = Feature::of(&name) {
106                        features |= feature;
107                    }
108                }
109                Ok(features)
110            }
111        }
112
113        d.deserialize_seq(Names)
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use serde::{Deserialize, Serialize};
120
121    use super::*;
122
123    /// A field as `Hello` and `ServerInfo` carry it.
124    #[derive(Debug, PartialEq, Serialize, Deserialize)]
125    struct Named(#[serde(with = "names")] Features);
126
127    #[test]
128    fn every_feature_is_named_once_and_read_back() {
129        let mut names: Vec<&str> = Features::all().iter().map(Feature::name).collect();
130        for feature in Features::all() {
131            assert_eq!(Feature::of(feature.name()), Some(feature));
132            assert!(feature.name().starts_with("spoolframe:"), "{feature}");
133        }
134        names.sort_unstable();
135        names.dedup();
136        assert_eq!(names.len(), Features::all().len());
137        assert_eq!(Feature::of("spoolframe:teleport"), None);
138    }
139
140    /// What is on for a connection: those both sides named.
141    #[test]
142    fn on_is_what_both_named() {
143        let client = Feature::ProfileEvents | Feature::InvitePasskeys;
144        let server = Feature::InvitePasskeys | Feature::WatchEvents;
145        assert_eq!(client & server, Feature::InvitePasskeys);
146        assert!((client & Features::empty()).is_empty());
147    }
148
149    /// Only names cross the wire, in JSON and in CBOR.
150    #[test]
151    fn a_set_goes_as_the_list_of_its_names() {
152        let set = Named(Feature::ProfileEvents | Feature::InvitePasskeys);
153        assert_eq!(
154            serde_json::to_value(&set).unwrap(),
155            serde_json::json!(["spoolframe:profile-events", "spoolframe:invite-passkeys"])
156        );
157        let cbor = crate::codec::encode(&set).unwrap();
158        let value: ciborium::Value = ciborium::from_reader(cbor.as_slice()).unwrap();
159        assert_eq!(
160            value,
161            ciborium::Value::Array(vec![
162                "spoolframe:profile-events".into(),
163                "spoolframe:invite-passkeys".into(),
164            ])
165        );
166        assert_eq!(crate::codec::decode::<Named>(&cbor).unwrap(), set);
167    }
168
169    /// A name this build does not know is skipped; the rest are read.
170    #[test]
171    fn an_unknown_name_is_skipped() {
172        let names = vec!["spoolframe:teleport", "spoolframe:watch-events"];
173        let read: Named = serde_json::from_value(serde_json::json!(names)).unwrap();
174        assert_eq!(read, Named(Feature::WatchEvents.into()));
175        let cbor = crate::codec::encode(&names).unwrap();
176        assert_eq!(
177            crate::codec::decode::<Named>(&cbor).unwrap(),
178            Named(Feature::WatchEvents.into())
179        );
180    }
181}