Skip to main content

spoolframe_protocol/federation/
replication.rs

1//! Replication: what a paired server asks of the one whose
2//! libraries are shared with it, and the answers. Only a live pair's
3//! connection reaches these; anyone else's stream is reset.
4//!
5//! The sharing server keeps no change feed and no poller. The server it
6//! shares with asks for each shared library with [`SyncLibrary`], and the
7//! sharing server walks the library then. It diffs what it finds against
8//! what it last gave that server, kept per pair and library as a content
9//! hash per item ([`RemoteItem::hash`]). It answers with the changes, or
10//! with the whole library when it does not know the cursor. Either answer
11//! comes as [`SyncPage`]s on the request's own stream, as many frames as it
12//! takes. The asking server keeps none of it until the last page is read,
13//! and then names the cursor in its next `SyncLibrary`.
14//!
15//! Every list here is bounded, and what a server reads of a page is cut
16//! to the bounds ([`SyncPage::within_bounds`]): a longer list loses its
17//! tail, a longer text its end.
18
19use serde::{Deserialize, Serialize};
20
21/// The most items one [`SyncPage`] carries; the rest are left out.
22pub const MAX_PAGE_ITEMS: usize = 200;
23
24/// The most ids of removed items one [`SyncPage`] carries.
25pub const MAX_PAGE_REMOVED: usize = 2_000;
26
27/// The most libraries a [`PeerReply::Libraries`](super::PeerReply) lists.
28pub const MAX_SHARED_LIBRARIES: usize = 256;
29
30/// The most artwork, external ids and genres one item carries.
31pub const MAX_ITEM_ARTWORK: usize = 8;
32pub const MAX_ITEM_EXTERNAL_IDS: usize = 16;
33pub const MAX_ITEM_GENRES: usize = 16;
34
35/// The longest title, name or short text an item carries, in characters.
36pub const MAX_ITEM_TEXT: usize = 512;
37
38/// The longest summary an item carries, in characters.
39pub const MAX_ITEM_SUMMARY: usize = 8_192;
40
41/// The largest image an [`ArtworkFetch`] is answered with, in bytes.
42pub const MAX_ARTWORK_BYTES: usize = 16 << 20;
43
44/// The largest reply to an [`ArtworkFetch`] a server reads, in bytes: the
45/// image's [`MAX_ARTWORK_BYTES`] and room for its media type and the
46/// reply around it. One announced longer is refused before any of it is
47/// held, not read to the reply's own 64 MiB bound first.
48pub const MAX_ARTWORK_REPLY: usize = MAX_ARTWORK_BYTES + (64 << 10);
49
50/// Ask for one shared library's changes since `since`.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub struct SyncLibrary {
53    /// The library's id, as the sharing server knows it
54    /// ([`SharedLibrary::id`]).
55    pub library: String,
56    /// The cursor the last whole answer gave; `None` the first time. One
57    /// the sharing server does not know is answered with the whole
58    /// library.
59    #[serde(default)]
60    pub since: Option<String>,
61}
62
63/// Ask for one image of a shared library's item, by the id an item's
64/// [`RemoteArtwork`] gave. Answered with
65/// [`PeerReply::Artwork`](super::PeerReply), written as a reply
66/// ([`crate::codec::write_reply`]) rather than a frame, as an image may be
67/// larger than one.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69pub struct ArtworkFetch {
70    pub id: String,
71}
72
73/// What a library holds, as a sharing server says.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
75#[serde(rename_all = "snake_case")]
76pub enum RemoteLibraryKind {
77    Movies,
78    Shows,
79    Music,
80    /// A kind this build does not know: not cached.
81    #[serde(other)]
82    Unknown,
83}
84
85impl RemoteLibraryKind {
86    /// Its name on the wire; `None` for one this build does not know.
87    pub fn as_str(self) -> Option<&'static str> {
88        Some(match self {
89            RemoteLibraryKind::Movies => "movies",
90            RemoteLibraryKind::Shows => "shows",
91            RemoteLibraryKind::Music => "music",
92            RemoteLibraryKind::Unknown => return None,
93        })
94    }
95}
96
97/// A library shared with the server asking.
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99pub struct SharedLibrary {
100    /// Its id on the sharing server.
101    pub id: String,
102    /// What the sharing server calls it.
103    pub title: String,
104    pub kind: RemoteLibraryKind,
105}
106
107/// What an item is.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
109#[serde(rename_all = "snake_case")]
110pub enum RemoteKind {
111    Movie,
112    Show,
113    Season,
114    Episode,
115    Artist,
116    Album,
117    Track,
118    /// A kind this build does not know: left out.
119    #[serde(other)]
120    Unknown,
121}
122
123impl RemoteKind {
124    /// Its name on the wire; `None` for one this build does not know.
125    pub fn as_str(self) -> Option<&'static str> {
126        Some(match self {
127            RemoteKind::Movie => "movie",
128            RemoteKind::Show => "show",
129            RemoteKind::Season => "season",
130            RemoteKind::Episode => "episode",
131            RemoteKind::Artist => "artist",
132            RemoteKind::Album => "album",
133            RemoteKind::Track => "track",
134            RemoteKind::Unknown => return None,
135        })
136    }
137}
138
139/// The role a piece of artwork plays.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
141#[serde(rename_all = "snake_case")]
142pub enum RemoteArtworkKind {
143    Poster,
144    Background,
145    Thumb,
146    /// A role this build does not know: left out.
147    #[serde(other)]
148    Unknown,
149}
150
151impl RemoteArtworkKind {
152    /// Its name on the wire; `None` for one this build does not know.
153    pub fn as_str(self) -> Option<&'static str> {
154        Some(match self {
155            RemoteArtworkKind::Poster => "poster",
156            RemoteArtworkKind::Background => "background",
157            RemoteArtworkKind::Thumb => "thumb",
158            RemoteArtworkKind::Unknown => return None,
159        })
160    }
161}
162
163/// A piece of an item's artwork, fetched with [`ArtworkFetch`].
164#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
165pub struct RemoteArtwork {
166    /// Its id on the sharing server.
167    pub id: String,
168    pub kind: RemoteArtworkKind,
169}
170
171/// One item of a shared library, as the sharing server has it. Ids are
172/// the sharing server's own; the server that caches it names them as its
173/// origin's (`spoolframe_types::MediaId::federated`).
174///
175/// Its place in the hierarchy: a season's `parent` is its show; an
176/// episode's `parent` its season and `grandparent` its show; an album's
177/// `parent` its artist; a track's `parent` its album and `grandparent` its
178/// artist. `index` is a season's number, an episode's, a track's;
179/// `parent_index` an episode's season number, a track's disc.
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181pub struct RemoteItem {
182    pub id: String,
183    pub kind: RemoteKind,
184    /// A title, or an artist's name.
185    pub title: String,
186    #[serde(default)]
187    pub parent: Option<String>,
188    #[serde(default)]
189    pub grandparent: Option<String>,
190    /// The parent's title: a season's or episode's show, an album's
191    /// artist, a track's album.
192    #[serde(default)]
193    pub parent_title: Option<String>,
194    /// The grandparent's: a track's artist.
195    #[serde(default)]
196    pub grandparent_title: Option<String>,
197    #[serde(default)]
198    pub index: Option<u32>,
199    #[serde(default)]
200    pub parent_index: Option<u32>,
201    #[serde(default)]
202    pub year: Option<u16>,
203    /// A film's release, an episode's air date, a show's last airing:
204    /// `YYYY-MM-DD`.
205    #[serde(default)]
206    pub date: Option<String>,
207    #[serde(default)]
208    pub summary: Option<String>,
209    #[serde(default)]
210    pub content_rating: Option<String>,
211    #[serde(default)]
212    pub duration_ms: Option<u64>,
213    /// A show's season count, an album's track count, a track's album's.
214    #[serde(default)]
215    pub count: Option<u32>,
216    #[serde(default)]
217    pub genres: Vec<String>,
218    #[serde(default)]
219    pub artwork: Vec<RemoteArtwork>,
220    /// Its stable ids outside the sharing server's keys: TMDB, IMDb,
221    /// TVDB, MusicBrainz, Plex's guid (`tmdb://603`). What progress per
222    /// title and merged search match on.
223    #[serde(default)]
224    pub external_ids: Vec<String>,
225    /// What a library is sorted and filtered by
226    /// ([`spoolframe_types::browse`]), each left out when the sharing
227    /// server has none. An older server sends none, and the item hashes
228    /// as if they were absent. A film's, a show's or an artist's.
229    #[serde(default, skip_serializing_if = "Option::is_none")]
230    pub sort_title: Option<String>,
231    /// The day it first came out, `YYYY-MM-DD`: a film's release, a
232    /// show's first airing (where `date` is its last).
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub released: Option<String>,
235    /// When it was added to the sharing server's catalog, Unix seconds.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub added_at: Option<i64>,
238    /// The critic rating, in tenths: 0 to 100.
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub rating_tenths: Option<u16>,
241    /// The audience rating, in tenths: 0 to 100.
242    #[serde(default, skip_serializing_if = "Option::is_none")]
243    pub audience_rating_tenths: Option<u16>,
244    /// Whose each rating is (`spoolframe:rating-sources` on the client
245    /// side); left out when not known, and by an older server.
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub rating_source: Option<spoolframe_types::RatingSource>,
248    #[serde(default, skip_serializing_if = "Option::is_none")]
249    pub audience_rating_source: Option<spoolframe_types::RatingSource>,
250    /// A film's file size, its first version's, in bytes.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub size: Option<u64>,
253    /// A film's resolution class, its first version's.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub resolution: Option<spoolframe_types::Resolution>,
256    /// A film's dynamic range, its first version's: `sdr`, `hdr` (not
257    /// Dolby Vision) or `dolby_vision`.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub dynamic_range: Option<spoolframe_types::DynamicRange>,
260    /// The content hash ([`RemoteItem::digest`]) the sharing server
261    /// diffed by: unchanged, unchanged item.
262    pub hash: String,
263}
264
265/// `text` cut to `max` characters.
266fn cut(text: &mut String, max: usize) {
267    if let Some((at, _)) = text.char_indices().nth(max) {
268        text.truncate(at);
269    }
270}
271
272fn cut_option(text: &mut Option<String>, max: usize) {
273    if let Some(text) = text {
274        cut(text, max);
275    }
276}
277
278impl RemoteItem {
279    /// The content hash of everything but `hash`: blake3, hex. Two items
280    /// with the same hash are the same item, as far as a cache can tell.
281    pub fn digest(&self) -> String {
282        let unhashed = RemoteItem {
283            hash: String::new(),
284            ..self.clone()
285        };
286        let bytes = crate::codec::encode(&unhashed).expect("an item encodes");
287        blake3::hash(&bytes).to_hex().to_string()
288    }
289
290    /// This item with `hash` set to its [`RemoteItem::digest`].
291    pub fn hashed(mut self) -> Self {
292        self.hash = self.digest();
293        self
294    }
295
296    /// This item cut to the bounds: what a server keeps of one.
297    pub fn within_bounds(mut self) -> Self {
298        for text in [&mut self.id, &mut self.title, &mut self.hash] {
299            cut(text, MAX_ITEM_TEXT);
300        }
301        for text in [
302            &mut self.parent,
303            &mut self.grandparent,
304            &mut self.parent_title,
305            &mut self.grandparent_title,
306            &mut self.date,
307            &mut self.content_rating,
308            &mut self.sort_title,
309            &mut self.released,
310        ] {
311            cut_option(text, MAX_ITEM_TEXT);
312        }
313        cut_option(&mut self.summary, MAX_ITEM_SUMMARY);
314        self.genres.truncate(MAX_ITEM_GENRES);
315        self.artwork.truncate(MAX_ITEM_ARTWORK);
316        self.external_ids.truncate(MAX_ITEM_EXTERNAL_IDS);
317        for text in self
318            .genres
319            .iter_mut()
320            .chain(self.external_ids.iter_mut())
321            .chain(self.artwork.iter_mut().map(|a| &mut a.id))
322        {
323            cut(text, MAX_ITEM_TEXT);
324        }
325        self
326    }
327}
328
329/// What a sync's pages hold.
330#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
331#[serde(rename_all = "snake_case")]
332pub enum SyncMode {
333    /// What changed since the cursor asked about: items added or changed,
334    /// and the ids of those gone. What is not named is as it was.
335    Changes,
336    /// The whole library: what is not named is gone.
337    Snapshot,
338    /// A mode this build does not know: the answer is not used.
339    #[serde(other)]
340    Unknown,
341}
342
343/// One page of the answer to [`SyncLibrary`].
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
345pub struct SyncPage {
346    pub mode: SyncMode,
347    /// The cursor to name as `since` next time, once every page is read:
348    /// the same on each page.
349    pub cursor: String,
350    /// At most [`MAX_PAGE_ITEMS`].
351    #[serde(default)]
352    pub items: Vec<RemoteItem>,
353    /// Ids of items gone, with [`SyncMode::Changes`]; at most
354    /// [`MAX_PAGE_REMOVED`].
355    #[serde(default)]
356    pub removed: Vec<String>,
357    /// Another page follows on this stream.
358    #[serde(default)]
359    pub more: bool,
360}
361
362impl SyncPage {
363    /// This page cut to the bounds: what a server keeps of one.
364    pub fn within_bounds(mut self) -> Self {
365        cut(&mut self.cursor, MAX_ITEM_TEXT);
366        self.items.truncate(MAX_PAGE_ITEMS);
367        self.items = self
368            .items
369            .into_iter()
370            .map(RemoteItem::within_bounds)
371            .collect();
372        self.removed.truncate(MAX_PAGE_REMOVED);
373        for id in &mut self.removed {
374            cut(id, MAX_ITEM_TEXT);
375        }
376        self
377    }
378}
379
380/// The libraries listed cut to [`MAX_SHARED_LIBRARIES`], their texts to
381/// [`MAX_ITEM_TEXT`]: what a server keeps of a listing.
382pub fn libraries_within_bounds(mut libraries: Vec<SharedLibrary>) -> Vec<SharedLibrary> {
383    libraries.truncate(MAX_SHARED_LIBRARIES);
384    for library in &mut libraries {
385        cut(&mut library.id, MAX_ITEM_TEXT);
386        cut(&mut library.title, MAX_ITEM_TEXT);
387    }
388    libraries
389}