spoolframe_protocol/federation/replication.rs
1//! Replication (P8-02): 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 server that shares (SA) keeps no change feed and no poller: the
6//! one it shares with (SB) asks for each shared library with [`SyncLibrary`],
7//! and SA walks the library then. It diffs what it finds against what it
8//! last gave SB, kept per pair and library as a content hash per item
9//! ([`RemoteItem::hash`]), and answers with the changes, or with the whole
10//! library when it does not know SB's cursor. Either answer comes as
11//! [`SyncPage`]s on the request's own stream, as many frames as it takes;
12//! SB keeps none of it until the last page is read, and then names the
13//! 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 (F8-12).
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 (P8-03) and merged search (P8-05) 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: one from before them sends none, and the item
228 /// hashes as it did. 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 /// A film's file size, its first version's, in bytes.
245 #[serde(default, skip_serializing_if = "Option::is_none")]
246 pub size: Option<u64>,
247 /// A film's resolution class, its first version's.
248 #[serde(default, skip_serializing_if = "Option::is_none")]
249 pub resolution: Option<spoolframe_types::Resolution>,
250 /// A film's dynamic range, its first version's: `sdr`, `hdr` (not
251 /// Dolby Vision) or `dolby_vision`.
252 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub dynamic_range: Option<spoolframe_types::DynamicRange>,
254 /// The content hash ([`RemoteItem::digest`]) the sharing server
255 /// diffed by: unchanged, unchanged item.
256 pub hash: String,
257}
258
259/// `text` cut to `max` characters.
260fn cut(text: &mut String, max: usize) {
261 if let Some((at, _)) = text.char_indices().nth(max) {
262 text.truncate(at);
263 }
264}
265
266fn cut_option(text: &mut Option<String>, max: usize) {
267 if let Some(text) = text {
268 cut(text, max);
269 }
270}
271
272impl RemoteItem {
273 /// The content hash of everything but `hash`: blake3, hex. Two items
274 /// with the same hash are the same item, as far as a cache can tell.
275 pub fn digest(&self) -> String {
276 let unhashed = RemoteItem {
277 hash: String::new(),
278 ..self.clone()
279 };
280 let bytes = crate::codec::encode(&unhashed).expect("an item encodes");
281 blake3::hash(&bytes).to_hex().to_string()
282 }
283
284 /// This item with `hash` set to its [`RemoteItem::digest`].
285 pub fn hashed(mut self) -> Self {
286 self.hash = self.digest();
287 self
288 }
289
290 /// This item cut to the bounds: what a server keeps of one.
291 pub fn within_bounds(mut self) -> Self {
292 for text in [&mut self.id, &mut self.title, &mut self.hash] {
293 cut(text, MAX_ITEM_TEXT);
294 }
295 for text in [
296 &mut self.parent,
297 &mut self.grandparent,
298 &mut self.parent_title,
299 &mut self.grandparent_title,
300 &mut self.date,
301 &mut self.content_rating,
302 &mut self.sort_title,
303 &mut self.released,
304 ] {
305 cut_option(text, MAX_ITEM_TEXT);
306 }
307 cut_option(&mut self.summary, MAX_ITEM_SUMMARY);
308 self.genres.truncate(MAX_ITEM_GENRES);
309 self.artwork.truncate(MAX_ITEM_ARTWORK);
310 self.external_ids.truncate(MAX_ITEM_EXTERNAL_IDS);
311 for text in self
312 .genres
313 .iter_mut()
314 .chain(self.external_ids.iter_mut())
315 .chain(self.artwork.iter_mut().map(|a| &mut a.id))
316 {
317 cut(text, MAX_ITEM_TEXT);
318 }
319 self
320 }
321}
322
323/// What a sync's pages hold.
324#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
325#[serde(rename_all = "snake_case")]
326pub enum SyncMode {
327 /// What changed since the cursor asked about: items added or changed,
328 /// and the ids of those gone. What is not named is as it was.
329 Changes,
330 /// The whole library: what is not named is gone.
331 Snapshot,
332 /// A mode this build does not know: the answer is not used.
333 #[serde(other)]
334 Unknown,
335}
336
337/// One page of the answer to [`SyncLibrary`].
338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
339pub struct SyncPage {
340 pub mode: SyncMode,
341 /// The cursor to name as `since` next time, once every page is read:
342 /// the same on each page.
343 pub cursor: String,
344 /// At most [`MAX_PAGE_ITEMS`].
345 #[serde(default)]
346 pub items: Vec<RemoteItem>,
347 /// Ids of items gone, with [`SyncMode::Changes`]; at most
348 /// [`MAX_PAGE_REMOVED`].
349 #[serde(default)]
350 pub removed: Vec<String>,
351 /// Another page follows on this stream.
352 #[serde(default)]
353 pub more: bool,
354}
355
356impl SyncPage {
357 /// This page cut to the bounds: what a server keeps of one.
358 pub fn within_bounds(mut self) -> Self {
359 cut(&mut self.cursor, MAX_ITEM_TEXT);
360 self.items.truncate(MAX_PAGE_ITEMS);
361 self.items = self
362 .items
363 .into_iter()
364 .map(RemoteItem::within_bounds)
365 .collect();
366 self.removed.truncate(MAX_PAGE_REMOVED);
367 for id in &mut self.removed {
368 cut(id, MAX_ITEM_TEXT);
369 }
370 self
371 }
372}
373
374/// The libraries listed cut to [`MAX_SHARED_LIBRARIES`], their texts to
375/// [`MAX_ITEM_TEXT`]: what a server keeps of a listing.
376pub fn libraries_within_bounds(mut libraries: Vec<SharedLibrary>) -> Vec<SharedLibrary> {
377 libraries.truncate(MAX_SHARED_LIBRARIES);
378 for library in &mut libraries {
379 cut(&mut library.id, MAX_ITEM_TEXT);
380 cut(&mut library.title, MAX_ITEM_TEXT);
381 }
382 libraries
383}