redseat-api 0.10.1

Rust client for Redseat media servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! A server copy against the mirror's fake server.

use serde_json::json;

use super::*;
use crate::mirror::MirrorOptions;
use crate::mirror::tests::{FakeServer, TempDir, media, sample_library, server_api, until};

/// A listener that records the changes it is told.
fn recorder() -> (impl OnChange, Arc<Mutex<Vec<Change>>>) {
    let changes = Arc::new(Mutex::new(Vec::new()));
    let kept = Arc::clone(&changes);
    let listener = move |change: &Change| {
        kept.lock().unwrap().push(change.clone());
    };
    (listener, changes)
}

async fn open(dir: &TempDir) -> (ServerCopy, Arc<Mutex<Vec<Change>>>) {
    let (listener, changes) = recorder();
    let path = dir.0.join("server").join("mirror.db");
    let copy = ServerCopy::open(MirrorOptions::new(path), listener)
        .await
        .unwrap();
    (copy, changes)
}

fn connect(copy: &ServerCopy, fake: &Arc<FakeServer>) {
    let fake = Arc::clone(fake);
    copy.connect(async move { Ok::<_, Error>(server_api(fake)) });
}

/// The library's view once its sync ended.
async fn synced(copy: &ServerCopy, library: &str) -> LibraryView {
    until("the library synced", async || {
        !copy.library(library).await.unwrap().syncing
    })
    .await;
    copy.library(library).await.unwrap()
}

#[tokio::test]
async fn a_first_sync_shows_its_progress_then_the_medias() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, changes) = open(&dir).await;
    assert_eq!(copy.reach(), Reach::Disconnected);

    // The library's requests wait: its first sync stays under way.
    *fake.gated.lock().unwrap() = Some("photos".into());
    let gate = fake.gate.lock().await;
    copy.focus(Some("photos"));
    connect(&copy, &fake);
    let first = copy.library("photos").await.unwrap();
    assert!(first.syncing && first.copying, "{first:?}");
    assert_eq!((first.count, first.sync_detail.is_empty()), (0, false));
    assert_eq!(copy.mirror().priority().as_deref(), Some("photos"));
    // A read does not change what syncs first.
    copy.focus(None);
    copy.library("photos").await.unwrap();
    assert_eq!(copy.mirror().priority(), None);
    copy.focus(Some("photos"));

    drop(gate);
    let done = synced(&copy, "photos").await;
    assert_eq!(done.count, 3);
    assert!(!done.copying && done.sync_detail.is_empty() && done.sync_percent.is_none());
    assert!(done.revision > first.revision, "the grid reads its medias");
    assert_eq!(copy.reach(), Reach::Connected);

    // Read again, nothing changed: the same revision.
    assert_eq!(
        copy.library("photos").await.unwrap().revision,
        done.revision
    );
    let ids: Vec<String> = (copy
        .medias("photos", &grid_query(), 0, 10)
        .await
        .unwrap()
        .into_iter())
    .map(|m| m.item.id)
    .collect();
    assert_eq!(ids, ["m3", "m2", "m1"], "newest first");

    until("the changes told", async || {
        let changes = changes.lock().unwrap();
        changes.contains(&Change::Server)
            && (changes.iter())
                .any(|c| c.library() == Some("photos") && c.touches(SyncKind::Medias))
    })
    .await;
}

#[tokio::test]
async fn a_library_holds_still_while_it_syncs_again() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, _) = open(&dir).await;
    connect(&copy, &fake);
    let before = synced(&copy, "photos").await;

    *fake.gated.lock().unwrap() = Some("photos".into());
    let gate = fake.gate.lock().await;
    fake.edit("photos", |library| {
        library.medias.push(media("m4", 400, json!({})));
    });
    copy.mirror().sync_library("photos");
    until("the sync started", async || copy.syncing("photos")).await;
    let held = copy.library("photos").await.unwrap();
    assert!(held.syncing && !held.copying, "a small sync shows the grid");
    assert_eq!((held.count, held.revision), (before.count, before.revision));

    drop(gate);
    let after = synced(&copy, "photos").await;
    assert_eq!(after.count, 4);
    assert!(after.revision > before.revision);
}

#[tokio::test]
async fn a_sync_over_between_two_reads_brings_a_new_revision() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, _) = open(&dir).await;
    connect(&copy, &fake);
    let before = synced(&copy, "photos").await;

    // Same count, another order: m1 becomes the newest.
    fake.edit("photos", |library| {
        library.medias[0] = media("m1", 400, json!({}));
    });
    copy.mirror().sync_library("photos");
    until("the copy has the edit", async || {
        copy.medias("photos", &grid_query(), 0, 1).await.unwrap()[0]
            .item
            .id
            == "m1"
    })
    .await;
    until("the sync ended", async || !copy.syncing("photos")).await;
    let after = copy.library("photos").await.unwrap();
    assert_eq!(after.count, before.count);
    assert!(after.revision > before.revision);
}

#[tokio::test]
async fn a_live_change_names_its_items() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, changes) = open(&dir).await;
    connect(&copy, &fake);
    synced(&copy, "photos").await;
    until("the event stream", async || fake.has_event_stream()).await;
    // The first sync's own change, told at the end of its burst.
    until_told(&changes, "photos").await;
    changes.lock().unwrap().clear();

    fake.send_event(
        "medias",
        "medias",
        json!({"library": "photos", "medias": [
            {"action": "updated", "media": media("m2", 500, json!({}))},
            {"action": "added", "media": media("m4", 500, json!({}))},
            {"action": "deleted", "media": media("m1", 500, json!({}))}
        ]}),
    );
    let told = until_told(&changes, "photos").await;
    let expected = ItemIds {
        added: ["m4".to_owned()].into(),
        updated: ["m2".to_owned()].into(),
        removed: ["m1".to_owned()].into(),
    };
    assert_eq!(
        told,
        BTreeMap::from([(SyncKind::Medias, Ids::Listed(expected))])
    );
    let change = Change::Library {
        library: "photos".into(),
        items: told,
    };
    assert!(change.ids(SyncKind::Medias).is_some() && change.ids(SyncKind::People).is_none());
    assert_eq!(Change::All.ids(SyncKind::People), Some(Ids::Many));
    assert_eq!(Change::Server.ids(SyncKind::Medias), None);
    let m2 = copy.media("photos", "m2").await.unwrap().unwrap();
    assert_eq!(m2.item.created, Some(500));
}

/// The items of the first [`Change::Library`] of `library` told.
async fn until_told(changes: &Mutex<Vec<Change>>, library: &str) -> BTreeMap<SyncKind, Ids> {
    let mut told = None;
    until("the change told", async || {
        told = (changes.lock().unwrap().iter()).find_map(|change| match change {
            Change::Library { library: l, items } if l == library && !items.is_empty() => {
                Some(items.clone())
            }
            _ => None,
        });
        told.is_some()
    })
    .await;
    told.unwrap()
}

#[test]
fn ids_merge_into_their_net_change() {
    let ids = |added: &[&str], updated: &[&str], removed: &[&str]| ItemIds {
        added: added.iter().map(|s| s.to_string()).collect(),
        updated: updated.iter().map(|s| s.to_string()).collect(),
        removed: removed.iter().map(|s| s.to_string()).collect(),
    };
    let mut burst = ids(&["new", "gone"], &["edited"], &["back"]);
    burst.merge(ids(&["back"], &["new", "edited"], &["gone", "edited"]));
    // Added then removed is nothing; removed then added again is updated; updated
    // then removed is removed.
    assert_eq!(burst, ids(&["new"], &["back"], &["edited"]));
    // Each id in one set at most.
    let mut odd = ids(&[], &["u"], &["r"]);
    odd.merge(ids(&["u"], &["r"], &[]));
    assert_eq!(odd, ids(&[], &["r", "u"], &[]));

    let mut listed = Ids::Listed(ItemIds::default());
    let many: Vec<String> = (0..=MAX_IDS).map(|i| i.to_string()).collect();
    listed.merge(ids(
        &[],
        &many.iter().map(String::as_str).collect::<Vec<_>>(),
        &[],
    ));
    assert_eq!(listed, Ids::Many);
}

#[tokio::test]
async fn a_failed_connection_waits_for_a_retry() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, _) = open(&dir).await;
    copy.connect(async { Err::<ServerApi, _>("The server does not answer.") });
    until("offline", async || {
        matches!(copy.reach(), Reach::Offline { .. })
    })
    .await;
    assert_eq!(
        copy.reach(),
        Reach::Offline {
            reason: "The server does not answer.".into(),
            retry: true
        }
    );
    // Nothing to wait for: an empty copy answers at once.
    let started = std::time::Instant::now();
    copy.ready(None).await;
    assert!(started.elapsed() < Duration::from_secs(1));
    assert!(copy.libraries().await.unwrap().is_empty());

    connect(&copy, &fake);
    until("connected", async || copy.reach() == Reach::Connected).await;
    copy.ready(None).await;
    assert_eq!(copy.libraries().await.unwrap().len(), 1);

    copy.disconnect();
    assert_eq!(copy.reach(), Reach::Disconnected);
    assert!(copy.api().is_none());
}

/// A connection that never ends; `dropped` closes when it is dropped.
fn stalled() -> (
    impl Future<Output = Result<ServerApi>> + Send + 'static,
    tokio::sync::oneshot::Receiver<()>,
) {
    let (kept, dropped) = tokio::sync::oneshot::channel::<()>();
    let connecting = async move {
        let _kept = kept;
        std::future::pending::<Result<ServerApi>>().await
    };
    (connecting, dropped)
}

#[tokio::test]
async fn a_disconnect_while_connecting_is_told() {
    let dir = TempDir::new();
    let (copy, changes) = open(&dir).await;
    let (connecting, dropped) = stalled();
    copy.connect(connecting);
    until("the connection started", async || {
        !changes.lock().unwrap().is_empty()
    })
    .await;
    assert_eq!(copy.reach(), Reach::Connecting);
    changes.lock().unwrap().clear();

    copy.disconnect();
    assert_eq!(copy.reach(), Reach::Disconnected);
    until("the disconnect was told", async || {
        changes.lock().unwrap().contains(&Change::Server)
    })
    .await;
    // The connection under way stopped.
    assert!(dropped.await.is_err());
}

#[tokio::test]
async fn a_dropped_copy_stops_its_connection() {
    let dir = TempDir::new();
    let (copy, _) = open(&dir).await;
    let (connecting, dropped) = stalled();
    copy.connect(connecting);
    drop(copy);
    let stopped = tokio::time::timeout(Duration::from_secs(5), dropped).await;
    assert!(matches!(stopped, Ok(Err(_))), "the connection still runs");
}

#[tokio::test]
async fn files_are_located_on_the_base_url_without_a_connection() {
    let dir = TempDir::new();
    let (copy, _) = open(&dir).await;
    assert!(
        copy.locate("l", "m", &Default::default(), false)
            .await
            .is_none()
    );
    copy.set_base(AuthorizedUrl {
        url: "http://s".into(),
        token: "t".into(),
        expires: 0,
    });
    let query = MediaFileQuery {
        unsupported_mime: vec!["all".into()],
        ..Default::default()
    };
    let located = copy.locate("l", "m", &query, false).await.unwrap();
    assert_eq!(
        (located.url.as_str(), located.token.as_str()),
        ("http://s/libraries/l/medias/m?unsupportedMime=all", "t")
    );

    // After a disconnect, no file is located with the old token.
    copy.disconnect();
    assert!(copy.base().is_none());
    assert!(copy.locate("l", "m", &query, false).await.is_none());
}

#[tokio::test]
async fn a_library_gone_from_the_server_is_not_waited_for() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, _) = open(&dir).await;
    connect(&copy, &fake);
    synced(&copy, "photos").await;
    let started = std::time::Instant::now();
    let gone = copy.library("gone").await;
    assert!(matches!(gone, Err(Error::NotFound { .. })), "{gone:?}");
    assert!(started.elapsed() < Duration::from_secs(2), "waited for it");
}

#[tokio::test]
async fn an_empty_library_syncing_again_shows_its_grid() {
    let dir = TempDir::new();
    let mut empty = sample_library("movies");
    empty.medias.clear();
    let fake = FakeServer::new(vec![empty]);
    let (copy, _) = open(&dir).await;
    connect(&copy, &fake);
    synced(&copy, "movies").await;

    *fake.gated.lock().unwrap() = Some("movies".into());
    let gate = fake.gate.lock().await;
    copy.mirror().sync_library("movies");
    until("the sync started", async || copy.syncing("movies")).await;
    let view = copy.library("movies").await.unwrap();
    assert!(view.syncing && !view.copying, "{view:?}");
    drop(gate);
}

#[tokio::test]
async fn a_sync_with_nothing_new_tells_no_items() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, changes) = open(&dir).await;
    connect(&copy, &fake);
    synced(&copy, "photos").await;
    until_told(&changes, "photos").await;
    tokio::time::sleep(BURST * 2).await;
    changes.lock().unwrap().clear();

    // The server sends the last items again (its pages overlap): nothing changed.
    copy.mirror().sync_library("photos");
    synced(&copy, "photos").await;
    tokio::time::sleep(BURST * 2).await;
    let told: Vec<Change> = changes.lock().unwrap().clone();
    assert!(
        told.iter()
            .all(|c| !matches!(c, Change::Library { items, .. } if !items.is_empty())),
        "{told:?}"
    );
}

#[tokio::test]
async fn names_are_read_once_until_the_library_changes() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, _) = open(&dir).await;
    connect(&copy, &fake);
    synced(&copy, "photos").await;
    let names = copy.names("photos").await.unwrap();
    assert!(Arc::ptr_eq(&names, &copy.names("photos").await.unwrap()));
    let medias = copy.medias("photos", &grid_query(), 0, 10).await.unwrap();
    let m1 = medias.iter().find(|m| m.item.id == "m1").unwrap();
    let rows = super::super::details::details(m1, &names);
    assert!(
        rows.iter()
            .any(|d| d.label == "People" && d.value == "Alice")
    );
}

#[test]
fn names_read_before_a_change_are_not_kept() {
    let mut cache = NamesCache::default();
    let names = Arc::new(Names::default());
    let generation = cache.generation;
    // A person renamed while the names were read.
    cache.forget(Some("photos"));
    cache.keep("photos", generation, false, &names);
    assert!(cache.libraries.is_empty());
    cache.keep("photos", cache.generation, false, &names);
    assert!(cache.get("photos", false).is_some());
}

#[test]
fn names_read_while_locked_are_read_again_once_unlocked() {
    let mut cache = NamesCache::default();
    let encrypted = Arc::new(Names::default());
    cache.keep("vault", cache.generation, false, &encrypted);
    assert!(cache.get("vault", false).is_some());
    // The passphrase is set: the names kept are still encrypted.
    assert!(cache.get("vault", true).is_none());
    let decrypted = Arc::new(Names::default());
    cache.keep("vault", cache.generation, true, &decrypted);
    let kept = cache.get("vault", true).unwrap();
    assert!(Arc::ptr_eq(&kept, &decrypted));
}

#[test]
fn libraries_sort_by_type_then_name() {
    let library = |id: &str, name: &str, kind: &str| -> ServerLibraryForRead {
        serde_json::from_value(json!({"id": id, "name": name, "type": kind})).unwrap()
    };
    let mut libraries = vec![
        library("1", "Films", "movies"),
        library("2", "travel", "photos"),
        library("3", "Family", "photos"),
    ];
    sort_libraries(&mut libraries);
    let ids: Vec<&str> = libraries.iter().map(|l| l.id.as_str()).collect();
    assert_eq!(ids, ["3", "2", "1"]);
    // References sort the same way.
    let mut refs: Vec<&ServerLibraryForRead> = libraries.iter().rev().collect();
    sort_libraries(&mut refs);
    assert_eq!(refs[0].id, "3");
}

#[test]
fn file_urls_escape_their_ids_and_carry_no_token() {
    assert_eq!(
        thumb_url("https://s.example:443", "lib 1", "m/2", 3),
        "https://s.example:443/libraries/lib%201/medias/m%2F2/image?size=thumb&v=3"
    );
    assert_eq!(
        media_file_url("http://s", "l", "m", &Default::default()),
        "http://s/libraries/l/medias/m"
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn reads_work_from_a_thread_outside_tokio() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, _) = open(&dir).await;
    connect(&copy, &fake);
    synced(&copy, "photos").await;

    // An app's UI thread: no tokio runtime there.
    let reader = copy.clone();
    let thread = std::thread::spawn(move || {
        crate::mirror::runtime::tests::block_on(async move {
            let view = reader.library("photos").await.unwrap();
            let medias = reader.medias("photos", &grid_query(), 0, 10).await.unwrap();
            let m1 = medias.iter().find(|m| m.item.id == "m1").unwrap();
            let related = reader.related("photos", m1).await.unwrap();
            let thumb = reader.mirror().thumb("photos", &m1.item).await.unwrap();
            (view.count, medias.len(), related.people.len(), thumb.len())
        })
    });
    let read = tokio::task::spawn_blocking(move || thread.join().unwrap())
        .await
        .unwrap();
    assert_eq!(read, (3, 3, 1, 10));
}

#[tokio::test]
async fn a_new_token_is_told_as_a_server_change() {
    let dir = TempDir::new();
    let fake = FakeServer::new(vec![sample_library("photos")]);
    let (copy, changes) = open(&dir).await;
    connect(&copy, &fake);
    synced(&copy, "photos").await;
    let first = copy.base().unwrap();

    // Read again, the same: nothing told.
    tokio::time::sleep(BURST * 2).await;
    changes.lock().unwrap().clear();
    copy.refresh_base().await;
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert!(!changes.lock().unwrap().contains(&Change::Server));

    copy.api().unwrap().client().set_token(crate::ServerToken {
        token: "renewed".into(),
        expires: i64::MAX,
    });
    copy.refresh_base().await;
    assert_eq!(copy.base().unwrap().token, "renewed");
    assert_ne!(copy.base().unwrap(), first);
    until("the change told", async || {
        changes.lock().unwrap().contains(&Change::Server)
    })
    .await;
}