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. One is gated all the same, at
15//! the owner's word: `spoolframe:rating-sources`'s, which a server leaves
16//! out of its replies to a connection without the feature. Nothing is decided from a
17//! version number. Unlike the experimental features
18//! ([`crate::experimental`]), these are ordinary protocol, with its
19//! stability, and a server that has one always names it when asked.
20//!
21//! The scheme is dated: a feature is what was added by its date, whatever
22//! the mix, so a client names one thing for all of it. Later additions get
23//! a new dated name; the one a release has shipped never changes what it
24//! holds, and a name stays once added.
25//!
26//! [`Hello::features`]: crate::Hello::features
27//! [`ServerInfo::features`]: crate::ServerInfo::features
28
29use std::fmt;
30
31use enumset::{EnumSet, EnumSetType};
32
33/// A regular feature. On the wire it is its name ([`Feature::name`]).
34#[derive(Debug, Hash, PartialOrd, Ord, EnumSetType)]
35#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
36#[non_exhaustive]
37pub enum Feature {
38 /// `spoolframe:october-2026`: `ProfileRemoved`, `PinChanged` and
39 /// `WatchChanged` on the events stream, `NextEpisode`, `ShowNext`, and
40 /// `BeginInvitePasskey` and `RedeemInviteWithPasskey`, an account made
41 /// with an invite and an app passkey.
42 October2026,
43 /// `spoolframe:download-addons`: `DownloadAddonOptions`,
44 /// `ReadTrackSubtitle` and `PrepareAudioAddon`, a subtitle as WebVTT
45 /// and an audio track as a file of its own, added to a download the
46 /// device has without fetching the film again.
47 ///
48 /// Not dated, unlike the scheme above says: the user chose this name
49 /// on purpose (2026-11-09), as a feature of its own that a client may
50 /// name without the rest of a month's.
51 DownloadAddons,
52 /// `spoolframe:diagnostics`: `SendDiagnostics`, an app's playback log
53 /// and what it runs on, kept on the server for its admins to read.
54 ///
55 /// Not dated, as `spoolframe:download-addons` is not: a feature of its
56 /// own that an app names without the rest of a month's.
57 Diagnostics,
58 /// `spoolframe:phone-sign-in`: `OfferDeviceSignIn`, a sign-in a
59 /// phone makes for a TV it reached directly
60 /// ([`crate::phone_sign_in`]), which the TV redeems with
61 /// `AwaitDeviceSignIn`.
62 ///
63 /// Not dated, as `spoolframe:diagnostics` is not: a feature of its
64 /// own that an app names without the rest of a month's.
65 PhoneSignIn,
66 /// `spoolframe:recently-played-row`: `RecentlyPlayedRow`, Home's one
67 /// "Recently played" row of every kind, music by where each play was
68 /// started ([`crate::recently_played`]), and
69 /// `RecentlyPlayedPreferences` and `SetRecentlyPlayedPreferences`,
70 /// how each kind shows in it. Named for what it brings, as
71 /// `spoolframe:diagnostics` is.
72 RecentlyPlayedRow,
73 /// `spoolframe:rating-sources`: whose each rating is
74 /// (`MergeFacts.rating_source` and `audience_rating_source`): Rotten
75 /// Tomatoes with its verdict, IMDb, TMDB. A reply field, not a
76 /// request: a server leaves them out for a connection without it.
77 RatingSources,
78}
79
80/// A set of features: [`Features::all`] is every one this build knows,
81/// and `client & server` those on for a connection. Bit positions are
82/// this build's own; only names cross the wire ([`names`]).
83pub type Features = EnumSet<Feature>;
84
85impl Feature {
86 /// Its name on the wire: the one place the names are written.
87 pub const fn name(self) -> &'static str {
88 match self {
89 Feature::October2026 => "spoolframe:october-2026",
90 Feature::DownloadAddons => "spoolframe:download-addons",
91 Feature::Diagnostics => "spoolframe:diagnostics",
92 Feature::PhoneSignIn => "spoolframe:phone-sign-in",
93 Feature::RecentlyPlayedRow => "spoolframe:recently-played-row",
94 Feature::RatingSources => "spoolframe:rating-sources",
95 }
96 }
97
98 /// The feature named `name`, if this build knows it.
99 pub fn of(name: &str) -> Option<Feature> {
100 Features::all().iter().find(|f| f.name() == name)
101 }
102}
103
104impl fmt::Display for Feature {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 f.write_str(self.name())
107 }
108}
109
110/// [`Features`] on the wire, for `#[serde(with = "names")]`: the list
111/// of their names. A name this build does not know is skipped as it is
112/// read. Never enumset's own serde, which would send its bits.
113pub mod names {
114 use std::fmt;
115
116 use serde::de::{SeqAccess, Visitor};
117 use serde::ser::SerializeSeq;
118 use serde::{Deserializer, Serializer};
119
120 use super::{Feature, Features};
121
122 pub fn serialize<S: Serializer>(features: &Features, s: S) -> Result<S::Ok, S::Error> {
123 let mut names = s.serialize_seq(Some(features.len()))?;
124 for feature in features.iter() {
125 names.serialize_element(feature.name())?;
126 }
127 names.end()
128 }
129
130 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Features, D::Error> {
131 struct Names;
132
133 impl<'de> Visitor<'de> for Names {
134 type Value = Features;
135
136 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 f.write_str("a list of feature names")
138 }
139
140 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Features, A::Error> {
141 let mut features = Features::empty();
142 // Owned: CBOR text may come in chunks.
143 while let Some(name) = seq.next_element::<String>()? {
144 if let Some(feature) = Feature::of(&name) {
145 features |= feature;
146 }
147 }
148 Ok(features)
149 }
150 }
151
152 d.deserialize_seq(Names)
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use serde::{Deserialize, Serialize};
159
160 use super::*;
161
162 /// A field as `Hello` and `ServerInfo` carry it.
163 #[derive(Debug, PartialEq, Serialize, Deserialize)]
164 struct Named(#[serde(with = "names")] Features);
165
166 #[test]
167 fn every_feature_is_named_once_and_read_back() {
168 let mut names: Vec<&str> = Features::all().iter().map(Feature::name).collect();
169 for feature in Features::all() {
170 assert_eq!(Feature::of(feature.name()), Some(feature));
171 assert!(feature.name().starts_with("spoolframe:"), "{feature}");
172 }
173 names.sort_unstable();
174 names.dedup();
175 assert_eq!(names.len(), Features::all().len());
176 assert_eq!(Feature::of("spoolframe:teleport"), None);
177 }
178
179 /// The download add-ons' name is fixed: an app names it as it is.
180 #[test]
181 fn download_addons_is_named_as_the_apps_name_it() {
182 assert_eq!(
183 Feature::of("spoolframe:download-addons"),
184 Some(Feature::DownloadAddons)
185 );
186 }
187
188 /// The diagnostics' name is fixed: an app names it as it is.
189 #[test]
190 fn diagnostics_is_named_as_the_apps_name_it() {
191 assert_eq!(
192 Feature::of("spoolframe:diagnostics"),
193 Some(Feature::Diagnostics)
194 );
195 }
196
197 /// The phone sign-in's name is fixed: an app names it as it is.
198 #[test]
199 fn phone_sign_in_is_named_as_the_apps_name_it() {
200 assert_eq!(
201 Feature::of("spoolframe:phone-sign-in"),
202 Some(Feature::PhoneSignIn)
203 );
204 }
205
206 /// What is on for a connection: those both sides named.
207 #[test]
208 fn on_is_what_both_named() {
209 let both = Features::only(Feature::October2026);
210 assert_eq!(both & both, both);
211 assert!((both & Features::empty()).is_empty());
212 }
213
214 /// Only names cross the wire, in JSON and in CBOR.
215 #[test]
216 fn a_set_goes_as_the_list_of_its_names() {
217 let set = Named(Feature::October2026.into());
218 assert_eq!(
219 serde_json::to_value(&set).unwrap(),
220 serde_json::json!(["spoolframe:october-2026"])
221 );
222 let cbor = crate::codec::encode(&set).unwrap();
223 let value: ciborium::Value = ciborium::from_reader(cbor.as_slice()).unwrap();
224 assert_eq!(
225 value,
226 ciborium::Value::Array(vec!["spoolframe:october-2026".into()])
227 );
228 assert_eq!(crate::codec::decode::<Named>(&cbor).unwrap(), set);
229 }
230
231 /// A name this build does not know is skipped; the rest are read.
232 #[test]
233 fn an_unknown_name_is_skipped() {
234 let names = vec!["spoolframe:teleport", "spoolframe:october-2026"];
235 let read: Named = serde_json::from_value(serde_json::json!(names)).unwrap();
236 assert_eq!(read, Named(Feature::October2026.into()));
237 let cbor = crate::codec::encode(&names).unwrap();
238 assert_eq!(
239 crate::codec::decode::<Named>(&cbor).unwrap(),
240 Named(Feature::October2026.into())
241 );
242 }
243}