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 /// `spoolframe:download-addons`: `DownloadAddonOptions`,
42 /// `ReadTrackSubtitle` and `PrepareAudioAddon`, a subtitle as WebVTT
43 /// and an audio track as a file of its own, added to a download the
44 /// device has without fetching the film again.
45 ///
46 /// Not dated, unlike the scheme above says: the user chose this name
47 /// on purpose (2026-11-09), as a feature of its own that a client may
48 /// name without the rest of a month's.
49 DownloadAddons,
50 /// `spoolframe:diagnostics`: `SendDiagnostics`, an app's playback log
51 /// and what it runs on, kept on the server for its admins to read.
52 ///
53 /// Not dated, as `spoolframe:download-addons` is not: a feature of its
54 /// own that an app names without the rest of a month's.
55 Diagnostics,
56}
57
58/// A set of features: [`Features::all`] is every one this build knows,
59/// and `client & server` those on for a connection. Bit positions are
60/// this build's own; only names cross the wire ([`names`]).
61pub type Features = EnumSet<Feature>;
62
63impl Feature {
64 /// Its name on the wire: the one place the names are written.
65 pub const fn name(self) -> &'static str {
66 match self {
67 Feature::October2026 => "spoolframe:october-2026",
68 Feature::DownloadAddons => "spoolframe:download-addons",
69 Feature::Diagnostics => "spoolframe:diagnostics",
70 }
71 }
72
73 /// The feature named `name`, if this build knows it.
74 pub fn of(name: &str) -> Option<Feature> {
75 Features::all().iter().find(|f| f.name() == name)
76 }
77}
78
79impl fmt::Display for Feature {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 f.write_str(self.name())
82 }
83}
84
85/// [`Features`] on the wire, for `#[serde(with = "names")]`: the list
86/// of their names. A name this build does not know is skipped as it is
87/// read. Never enumset's own serde, which would send its bits.
88pub mod names {
89 use std::fmt;
90
91 use serde::de::{SeqAccess, Visitor};
92 use serde::ser::SerializeSeq;
93 use serde::{Deserializer, Serializer};
94
95 use super::{Feature, Features};
96
97 pub fn serialize<S: Serializer>(features: &Features, s: S) -> Result<S::Ok, S::Error> {
98 let mut names = s.serialize_seq(Some(features.len()))?;
99 for feature in features.iter() {
100 names.serialize_element(feature.name())?;
101 }
102 names.end()
103 }
104
105 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Features, D::Error> {
106 struct Names;
107
108 impl<'de> Visitor<'de> for Names {
109 type Value = Features;
110
111 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.write_str("a list of feature names")
113 }
114
115 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Features, A::Error> {
116 let mut features = Features::empty();
117 // Owned: CBOR text may come in chunks.
118 while let Some(name) = seq.next_element::<String>()? {
119 if let Some(feature) = Feature::of(&name) {
120 features |= feature;
121 }
122 }
123 Ok(features)
124 }
125 }
126
127 d.deserialize_seq(Names)
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use serde::{Deserialize, Serialize};
134
135 use super::*;
136
137 /// A field as `Hello` and `ServerInfo` carry it.
138 #[derive(Debug, PartialEq, Serialize, Deserialize)]
139 struct Named(#[serde(with = "names")] Features);
140
141 #[test]
142 fn every_feature_is_named_once_and_read_back() {
143 let mut names: Vec<&str> = Features::all().iter().map(Feature::name).collect();
144 for feature in Features::all() {
145 assert_eq!(Feature::of(feature.name()), Some(feature));
146 assert!(feature.name().starts_with("spoolframe:"), "{feature}");
147 }
148 names.sort_unstable();
149 names.dedup();
150 assert_eq!(names.len(), Features::all().len());
151 assert_eq!(Feature::of("spoolframe:teleport"), None);
152 }
153
154 /// The download add-ons' name is fixed: an app names it as it is.
155 #[test]
156 fn download_addons_is_named_as_the_apps_name_it() {
157 assert_eq!(
158 Feature::of("spoolframe:download-addons"),
159 Some(Feature::DownloadAddons)
160 );
161 }
162
163 /// The diagnostics' name is fixed: an app names it as it is.
164 #[test]
165 fn diagnostics_is_named_as_the_apps_name_it() {
166 assert_eq!(
167 Feature::of("spoolframe:diagnostics"),
168 Some(Feature::Diagnostics)
169 );
170 }
171
172 /// What is on for a connection: those both sides named.
173 #[test]
174 fn on_is_what_both_named() {
175 let both = Features::only(Feature::October2026);
176 assert_eq!(both & both, both);
177 assert!((both & Features::empty()).is_empty());
178 }
179
180 /// Only names cross the wire, in JSON and in CBOR.
181 #[test]
182 fn a_set_goes_as_the_list_of_its_names() {
183 let set = Named(Feature::October2026.into());
184 assert_eq!(
185 serde_json::to_value(&set).unwrap(),
186 serde_json::json!(["spoolframe:october-2026"])
187 );
188 let cbor = crate::codec::encode(&set).unwrap();
189 let value: ciborium::Value = ciborium::from_reader(cbor.as_slice()).unwrap();
190 assert_eq!(
191 value,
192 ciborium::Value::Array(vec!["spoolframe:october-2026".into()])
193 );
194 assert_eq!(crate::codec::decode::<Named>(&cbor).unwrap(), set);
195 }
196
197 /// A name this build does not know is skipped; the rest are read.
198 #[test]
199 fn an_unknown_name_is_skipped() {
200 let names = vec!["spoolframe:teleport", "spoolframe:october-2026"];
201 let read: Named = serde_json::from_value(serde_json::json!(names)).unwrap();
202 assert_eq!(read, Named(Feature::October2026.into()));
203 let cbor = crate::codec::encode(&names).unwrap();
204 assert_eq!(
205 crate::codec::decode::<Named>(&cbor).unwrap(),
206 Named(Feature::October2026.into())
207 );
208 }
209}