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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! The queue of the user's changes ([`Action`]): kept in the store with the copy,
//! applied to the copy at once, sent to the server in order when it can be reached.
//! Port of the phone app's `action-queue.ts`.
//!
//! - **Queueing** ([`Mirror::queue`]): under the copy's write lock, the action is
//! stored, the actions it replaces removed and the copy changed, in one store
//! transaction; the screens are told as for any change.
//! - **Sending** (`replay`): one runner at a time, while connected, in queue order.
//! Deletions of medias go together, and so do the same change of several medias
//! (`update_medias`). An item's actions go one after the other: one waits while an
//! older one is not done. A library whose passphrase is not set waits: its names are
//! encrypted when sent. Done or gone (404): removed, the server's answer written. The
//! server unreachable: kept, without counting. Refused (403, another 4xx): failed.
//! Another error: counted, failed after [`MAX_ATTEMPTS`]. Actions left for later are
//! tried again after a growing delay; failed ones at each new connection.
//! - **The sync** writes what the server sends with the waiting actions applied again
//! ([`super::actions::rebase`]), under the same lock: it never brings back a deleted
//! media nor undoes a change not sent yet. Once the server deleted a media, a page
//! read before still leaves it out (`Queue::drop_deleted`).
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use super::actions::{
Action, ActionCounts, ActionStatus, MAX_ATTEMPTS, QueuedAction, RebasedUndo, Undo, rebase,
};
use super::store::{Changes, Removal, SyncKind, Written};
use super::{Inner, MAX_RETRY_DELAY, Mirror, MirrorEvent, RETRY_DELAY};
use crate::client::now_ms;
use crate::error::{Error, ErrorKind, Result};
use crate::library::{LibraryApi, MediaItem};
use crate::types::ItemWithRelations;
use crate::types::episode::Episode;
use crate::types::media::Media;
use crate::types::movie::Movie;
/// Actions sent in one request at most: deletions, or one change of several medias.
pub const BATCH: usize = 100;
/// The queue as the mirror holds it: every library's actions, in order, as stored.
#[derive(Default)]
pub(super) struct Queue {
state: Mutex<QueueState>,
}
#[derive(Default)]
struct QueueState {
actions: Vec<QueuedAction>,
/// A runner sends the actions.
running: bool,
/// Asked again while running: the runner looks once more before it stops.
again: bool,
/// Runs in a row that left actions for later: the delay of the next.
failures: u32,
/// A later run is scheduled.
timer: bool,
/// The medias the server deleted for this app, by library: with the changes
/// started once it had ([`super::viewing::ViewingWrites::started`]). A page read
/// before may still have them.
deleted: HashMap<String, HashMap<String, u64>>,
}
impl Queue {
pub(super) fn new(actions: Vec<QueuedAction>) -> Queue {
Queue {
state: Mutex::new(QueueState {
actions,
..Default::default()
}),
}
}
fn lock(&self) -> MutexGuard<'_, QueueState> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Applies the actions waiting in `library`, but `sent`, to what the server sent. A
/// media whose deletion waits becomes what discarding the deletion puts back, when
/// newer than the one kept: the sync goes past it meanwhile. Returns the deletions
/// changed, to store, and the other actions' undo against what the server sent: to
/// keep for the items the copy takes ([`Queue::accept`]).
pub(super) fn rebase(
&self,
library: &str,
changes: &mut Changes,
sent: &[i64],
) -> (Vec<QueuedAction>, Vec<RebasedUndo>) {
let mut state = self.lock();
let waiting = state.actions.iter().filter(|a| !sent.contains(&a.id));
let rebased = rebase(waiting, library, changes);
let mut changed = Vec::new();
for (id, media) in rebased.left_out {
let Some(action) = state.actions.iter_mut().find(|a| a.id == id) else {
continue;
};
let kept =
(action.undo.as_ref())
.and_then(Undo::from_json)
.and_then(|undo| match undo {
Undo::Media { media } => media.item.modified,
_ => None,
});
if kept.is_none_or(|kept| media.item.modified.unwrap_or(0) >= kept) {
action.undo = Undo::Media {
media: Box::new(media),
}
.to_json();
changed.push(action.clone());
}
}
(changed, rebased.undos)
}
/// Keeps the undo found by [`Queue::rebase`] of the actions whose item the server
/// sent is `current` ([`Inner::current`]): discarding one puts back what the
/// server last sent. Returns the actions changed, to store.
pub(super) fn accept(
&self,
current: &HashSet<(SyncKind, String)>,
undos: Vec<RebasedUndo>,
) -> Vec<QueuedAction> {
let mut state = self.lock();
let mut changed = Vec::new();
for (id, kind, item, undo) in undos {
if !current.contains(&(kind, item)) {
continue;
}
if let Some(action) = state.actions.iter_mut().find(|a| a.id == id) {
let undo = undo.to_json();
if action.undo != undo {
action.undo = undo;
changed.push(action.clone());
}
}
}
changed
}
/// The actions waiting in `library`, not being sent, on an item the server removed
/// (`removals`): the copy removed it (`written`), or it is a media whose deletion
/// waits and the removal is not older than the media the deletion keeps (the
/// store's rule: an item modified after a removal came back since, and stays).
pub(super) fn gone(&self, library: &str, removals: &[Removal], written: &Written) -> Vec<i64> {
if removals.is_empty() {
return Vec::new();
}
let state = self.lock();
(state.actions.iter())
.filter(|a| a.library == library && a.status != ActionStatus::Sending)
.filter(|a| {
let (kind, id) = a.action.target();
let Some(removal) = removals.iter().find(|r| r.kind == kind && r.id == id) else {
return false;
};
if written
.get(&kind)
.is_some_and(|ids| ids.removed.contains(&id))
{
return true;
}
let kept = match &a.action {
Action::MediaDelete { .. } => a.undo.as_ref().and_then(Undo::from_json),
_ => None,
};
match kept {
Some(Undo::Media { media }) => {
(removal.date).is_none_or(|date| media.item.modified.unwrap_or(0) <= date)
}
_ => false,
}
})
.map(|a| a.id)
.collect()
}
/// Forgets actions the store removed.
pub(super) fn drop_actions(&self, ids: &[i64]) {
self.lock().actions.retain(|a| !ids.contains(&a.id));
}
/// The media a deletion waiting in `library` keeps, to put back if discarded.
pub(super) fn deleted_media(&self, library: &str, media: &str) -> Option<MediaItem> {
let state = self.lock();
let action = state.actions.iter().find(|a| {
a.library == library
&& matches!(&a.action, Action::MediaDelete { media: id } if id == media)
})?;
match action.undo.as_ref().and_then(Undo::from_json)? {
Undo::Media { media } => Some(*media),
_ => None,
}
}
/// Takes out of an item read from the copy what the actions waiting on it did, the
/// newest first, but those `sent` (the server has them): for the copy's values
/// that stand in for the server's in what it sent (relations an event or an answer
/// leaves out, the values `keep_viewing` keeps), so `rebase` makes the actions
/// again and finds their undo against what the server has.
pub(super) fn undo_waiting(
&self,
library: &str,
kind: SyncKind,
id: &str,
sent: &[i64],
mut undo: impl FnMut(Undo),
) {
let state = self.lock();
let waiting = (state.actions.iter().rev()).filter(|a| {
a.library == library
&& !sent.contains(&a.id)
&& a.action.target() == (kind, id.to_owned())
});
for action in waiting {
if let Some(value) = action.undo.as_ref().and_then(Undo::from_json) {
undo(value);
}
}
}
/// Drops from a page read from the server since `started` the medias it deleted
/// for this app after: the page is older than the deletion.
pub(super) fn drop_deleted(&self, library: &str, changes: &mut Changes, started: u64) {
let state = self.lock();
if let Some(deleted) = state.deleted.get(library) {
(changes.medias)
.retain(|media| deleted.get(&media.item.id).is_none_or(|at| started >= *at));
}
}
/// Forgets the actions of a removed library (the store removed them with it).
pub(super) fn forget(&self, library: &str) {
let mut state = self.lock();
state.actions.retain(|a| a.library != library);
state.deleted.remove(library);
}
}
/// What to do after an attempt.
enum Step {
/// On with the next actions.
Next,
/// These actions wait for a later run; on with the others.
Later,
/// The server cannot be reached: stop until a later run.
Stop,
}
/// How an error of the server counts.
enum Failure {
/// Not reached, or the user's credentials: not the action's fault.
Offline,
/// The server refuses the action: failed at once.
Refused,
/// Counted; failed after [`MAX_ATTEMPTS`].
Retry,
}
fn failure(error: &Error) -> Failure {
match error {
Error::Network { .. }
| Error::Timeout { .. }
| Error::Unauthorized { .. }
| Error::Cancelled { .. }
| Error::PassphraseRequired
| Error::Transport { status: None, .. } => Failure::Offline,
Error::Forbidden { .. }
| Error::Transport {
status: Some(_), ..
} => Failure::Refused,
_ => Failure::Retry,
}
}
/// The items queued actions change, read from the copy once, then changed in turn.
#[derive(Default)]
struct Items {
medias: HashMap<String, MediaItem>,
movies: HashMap<String, ItemWithRelations<Movie>>,
episodes: HashMap<String, Episode>,
changed: HashSet<(SyncKind, String)>,
removed: Vec<Removal>,
}
impl Items {
async fn read(
inner: &Inner,
library: &str,
ids: HashMap<SyncKind, Vec<String>>,
) -> Result<Self> {
let mut items = Items::default();
for (kind, ids) in ids {
match kind {
SyncKind::Medias => {
for media in inner.stored::<MediaItem>(library, kind, ids).await? {
items.medias.insert(media.item.id.clone(), media);
}
}
SyncKind::Movies => {
let movies = inner.stored::<ItemWithRelations<Movie>>(library, kind, ids);
for movie in movies.await? {
items.movies.insert(movie.item.id.clone(), movie);
}
}
SyncKind::Episodes => {
for episode in inner.stored::<Episode>(library, kind, ids).await? {
items.episodes.insert(episode.id(), episode);
}
}
_ => {}
}
}
Ok(items)
}
/// The ids of the items `actions` change, by kind.
fn targets<'a>(
actions: impl IntoIterator<Item = &'a Action>,
) -> HashMap<SyncKind, Vec<String>> {
let mut ids: HashMap<SyncKind, Vec<String>> = HashMap::new();
let mut seen = HashSet::new();
for action in actions {
let target = action.target();
if seen.insert(target.clone()) {
ids.entry(target.0).or_default().push(target.1);
}
}
ids
}
/// Makes an action's change; returns how to undo it (`None`: the copy does not
/// have its item).
fn apply(&mut self, action: &Action, at: i64) -> Option<Undo> {
let (kind, id) = action.target();
let undo = match kind {
SyncKind::Medias if matches!(action, Action::MediaDelete { .. }) => {
let media = self.medias.remove(&id)?;
self.changed.remove(&(kind, id.clone()));
self.removed.push(Removal {
kind,
id,
date: None,
});
return Some(Undo::Media {
media: Box::new(media),
});
}
SyncKind::Medias => action.apply_media(self.medias.get_mut(&id)?),
SyncKind::Movies => action.apply_movie(&mut self.movies.get_mut(&id)?.item, at),
SyncKind::Episodes => action.apply_episode(self.episodes.get_mut(&id)?, at),
_ => None,
};
self.changed.insert((kind, id));
undo
}
/// Puts back what an action changed.
fn undo(&mut self, action: &Action, undo: Undo) {
let (kind, id) = action.target();
match (kind, undo) {
(SyncKind::Medias, Undo::Media { media }) => {
self.removed.retain(|r| !(r.kind == kind && r.id == id));
self.medias.insert(id.clone(), *media);
}
(SyncKind::Medias, undo) => match self.medias.get_mut(&id) {
Some(media) => undo.undo_media(media),
None => return,
},
(SyncKind::Movies, undo) => match self.movies.get_mut(&id) {
Some(movie) => undo.undo_movie(&mut movie.item),
None => return,
},
(SyncKind::Episodes, undo) => match self.episodes.get_mut(&id) {
Some(episode) => undo.undo_episode(episode),
None => return,
},
_ => return,
}
self.changed.insert((kind, id));
}
fn into_changes(self) -> Changes {
let Items {
medias,
movies,
episodes,
changed,
removed,
} = self;
let changed = |kind, id: &String| changed.contains(&(kind, id.clone()));
Changes {
medias: (medias.into_iter())
.filter(|(id, _)| changed(SyncKind::Medias, id))
.map(|(_, media)| media)
.collect(),
movies: (movies.into_iter())
.filter(|(id, _)| changed(SyncKind::Movies, id))
.map(|(_, movie)| movie)
.collect(),
episodes: (episodes.into_iter())
.filter(|(id, _)| changed(SyncKind::Episodes, id))
.map(|(_, episode)| episode)
.collect(),
removed,
..Default::default()
}
}
}
impl Mirror {
/// Queues changes of the user's in `library`, in order: the copy changes at once
/// (told as any change), and the server gets them when it can be reached, now if
/// connected. A newer value of a field replaces one not sent yet
/// ([`Action::replaces`]); a deletion drops what waits for its media. Works offline;
/// the actions stay across restarts.
pub async fn queue(&self, library: &str, actions: Vec<Action>) -> Result<()> {
self.inner.queue_actions(library, actions).await
}
/// Deletes medias, with their files: gone from the copy at once, deleted on the
/// server when it can be reached ([`Self::queue`]).
pub async fn remove_medias(&self, library: &str, medias: &[String]) -> Result<()> {
let actions = (medias.iter())
.map(|media| Action::MediaDelete {
media: media.clone(),
})
.collect();
self.queue(library, actions).await
}
/// The actions not sent yet, or failed, in the order they are sent: of one library,
/// or of all.
pub fn actions(&self, library: Option<&str>) -> Vec<QueuedAction> {
(self.inner.queue.lock().actions.iter())
.filter(|a| library.is_none_or(|l| a.library == l))
.cloned()
.collect()
}
/// How many actions wait and how many failed: in one library, or in all.
pub fn pending(&self, library: Option<&str>) -> ActionCounts {
let state = self.inner.queue.lock();
let mut counts = ActionCounts::default();
for action in (state.actions.iter()).filter(|a| library.is_none_or(|l| a.library == l)) {
match action.status {
ActionStatus::Failed => counts.failed += 1,
_ => counts.pending += 1,
}
}
counts
}
/// The status of the actions on one item: failed when one failed, else pending
/// when one waits, else `None`. `id` as in [`Action::target`].
pub fn item_status(&self, library: &str, kind: SyncKind, id: &str) -> Option<ActionStatus> {
let state = self.inner.queue.lock();
let mut found = None;
for action in state.actions.iter().filter(|a| a.library == library) {
let (target_kind, target) = action.action.target();
if target_kind == kind && target == id {
match action.status {
ActionStatus::Failed => return Some(ActionStatus::Failed),
status => found = Some(status),
}
}
}
found
}
/// Sends a failed action again (now if connected).
pub async fn retry(&self, id: i64) -> Result<()> {
self.inner.retry(|a| a.id == id).await
}
/// Sends the failed actions again: of one library, or of all.
pub async fn retry_failed(&self, library: Option<&str>) -> Result<()> {
self.inner
.retry(|a| library.is_none_or(|l| a.library == l))
.await
}
/// Drops an action not being sent, and puts back in the copy what it changed: a
/// deleted media comes back, a tag added goes away, a rating or a name is the one
/// before.
pub async fn discard(&self, id: i64) -> Result<()> {
self.inner.discard(|a| a.id == id).await
}
/// Discards the failed actions: of one library, or of all.
pub async fn discard_failed(&self, library: Option<&str>) -> Result<()> {
self.inner
.discard(|a| a.status == ActionStatus::Failed && library.is_none_or(|l| a.library == l))
.await
}
}
impl Inner {
pub(super) async fn queue_actions(
self: &Arc<Self>,
library: &str,
actions: Vec<Action>,
) -> Result<()> {
if actions.is_empty() {
return Ok(());
}
if self.library(library).is_none() {
return Err(Error::NotFound {
message: format!("no library {library} in the local copy"),
path: None,
});
}
if actions.iter().any(Action::is_viewing) {
// A change of what the user watched started: a refresh page read before
// is read again (`ViewingWrites`).
drop(self.viewing.begin());
}
let written = {
let _write = self.viewing.write.lock().await;
let now = now_ms();
let mut items = Items::read(self, library, Items::targets(&actions)).await?;
let older: Vec<QueuedAction> = (self.queue.lock().actions.iter())
.filter(|old| old.library == library && old.status != ActionStatus::Sending)
.cloned()
.collect();
let mut replaced: Vec<i64> = Vec::new();
let mut queued: Vec<QueuedAction> = Vec::new();
for action in actions {
let mut undo = items.apply(&action, now);
// It puts back what was before the actions it replaces, the newest
// first: discarding it gives what was before the oldest.
for old in older
.iter()
.rev()
.filter(|old| action.replaces(&old.action))
{
if !replaced.contains(&old.id) {
replaced.push(old.id);
}
let old_undo = old.undo.as_ref().and_then(Undo::from_json);
if old.action.name() == action.name() {
undo = old_undo.or(undo);
} else if let (Some(Undo::Media { media }), Some(old_undo)) =
(undo.as_mut(), old_undo)
{
// A deletion: the media it keeps without the other change.
old_undo.undo_media(media);
}
}
queued.push(QueuedAction {
id: 0,
library: library.to_owned(),
action,
status: ActionStatus::Pending,
attempts: 0,
created: now,
attempted: None,
error: None,
undo: undo.and_then(|undo| undo.to_json()),
});
}
let generation = self.generation(library).await?;
let (ids, written) = (self.store)
.queue_actions(
library,
generation,
queued.clone(),
replaced.clone(),
items.into_changes(),
)
.await?;
let mut state = self.queue.lock();
state.actions.retain(|a| !replaced.contains(&a.id));
for (mut action, id) in queued.into_iter().zip(ids) {
action.id = id;
state.actions.push(action);
}
written
};
self.told(library, written).await?;
self.emit(MirrorEvent::Actions {
library: library.to_owned(),
});
self.replay();
Ok(())
}
/// Makes failed actions matching `select` pending again, then sends them.
pub(super) async fn retry(
self: &Arc<Self>,
select: impl Fn(&QueuedAction) -> bool,
) -> Result<()> {
let libraries = self
.update(|action| {
if action.status != ActionStatus::Failed || !select(action) {
return false;
}
action.status = ActionStatus::Pending;
action.attempts = 0;
action.error = None;
true
})
.await?;
for library in libraries {
self.emit(MirrorEvent::Actions { library });
}
self.replay();
Ok(())
}
/// Changes the actions `change` says it changed (`true`), in memory and in the
/// store; returns their libraries.
async fn update(
&self,
mut change: impl FnMut(&mut QueuedAction) -> bool,
) -> Result<Vec<String>> {
let _write = self.viewing.write.lock().await;
let changed: Vec<QueuedAction> = {
let mut state = self.queue.lock();
(state.actions.iter_mut())
.filter_map(|action| change(action).then(|| action.clone()))
.collect()
};
let mut libraries: Vec<String> = changed.iter().map(|a| a.library.clone()).collect();
libraries.dedup();
if !changed.is_empty() {
self.store.update_actions(changed).await?;
}
Ok(libraries)
}
/// Drops the actions matching `select` that are not being sent, and puts back what
/// they changed. The actions kept that change the same items are made again from
/// what was before them all, so their own undo stays right. Then sends what waited
/// behind the dropped ones.
async fn discard(self: &Arc<Self>, select: impl Fn(&QueuedAction) -> bool) -> Result<()> {
let mut told = Vec::new();
{
// Held until they are gone: the runner marks actions as being sent under
// it too (`next_batch`), so none of these starts meanwhile.
let _write = self.viewing.write.lock().await;
let chosen: Vec<QueuedAction> = (self.queue.lock().actions.iter())
.filter(|a| a.status != ActionStatus::Sending && select(a))
.cloned()
.collect();
let mut libraries: Vec<String> = chosen.iter().map(|a| a.library.clone()).collect();
libraries.sort();
libraries.dedup();
for library in libraries {
let dropped: Vec<&QueuedAction> =
chosen.iter().filter(|a| a.library == library).collect();
let ids: Vec<i64> = dropped.iter().map(|a| a.id).collect();
let targets: HashSet<_> = dropped.iter().map(|a| a.action.target()).collect();
let kept: Vec<QueuedAction> = (self.queue.lock().actions.iter())
.filter(|a| {
a.library == library
&& !ids.contains(&a.id)
&& targets.contains(&a.action.target())
})
.cloned()
.collect();
let read = Items::targets(dropped.iter().map(|a| &a.action));
let mut items = Items::read(self, &library, read).await?;
// The newest first: each puts back what was before it.
let mut all: Vec<&QueuedAction> = dropped.iter().copied().chain(&kept).collect();
all.sort_by_key(|a| a.id);
for action in all.iter().rev() {
if let Some(undo) = action.undo.as_ref().and_then(Undo::from_json) {
items.undo(&action.action, undo);
}
}
let undos: HashMap<i64, Option<serde_json::Value>> = (kept.iter())
.map(|a| {
let undo = items.apply(&a.action, a.created);
(a.id, undo.and_then(|undo| undo.to_json()))
})
.collect();
let generation = self.generation(&library).await?;
let written = (self.store)
.remove_actions(&library, generation, ids.clone(), items.into_changes())
.await?;
let redone: Vec<QueuedAction> = {
let mut state = self.queue.lock();
state.actions.retain(|a| !ids.contains(&a.id));
(state.actions.iter_mut())
.filter_map(|a| {
a.undo = undos.get(&a.id)?.clone();
Some(a.clone())
})
.collect()
};
if !redone.is_empty() {
self.store.update_actions(redone).await?;
}
told.push((library, written));
}
}
for (library, written) in told {
self.told(&library, written).await?;
self.emit(MirrorEvent::Actions { library });
}
self.replay();
Ok(())
}
/// Sends the waiting actions in the background, unless a runner does already.
/// Nothing while not connected: the next connection starts it.
pub(super) fn replay(self: &Arc<Self>) {
if self.lock().connection.is_none() {
return;
}
{
let mut state = self.queue.lock();
if !(state.actions.iter()).any(|a| a.status == ActionStatus::Pending) {
return;
}
if state.running {
state.again = true;
return;
}
state.running = true;
state.again = false;
}
let inner = self.clone();
self.runtime
.spawn(Box::pin(async move { inner.run_replay().await }));
}
/// At each new connection: the failed actions are tried again with the others.
pub(super) async fn reconnected(self: &Arc<Self>) {
let _ = self.retry(|_| true).await;
self.replay();
}
async fn run_replay(self: Arc<Self>) {
loop {
let mut later = false;
let mut skipped: HashSet<i64> = HashSet::new();
while let Some((api, batch)) = self.next_batch(&skipped).await {
let ids: Vec<i64> = batch.iter().map(|a| a.id).collect();
match self.attempt(&api, &batch).await {
Step::Next => {}
Step::Later => {
later = true;
skipped.extend(ids);
}
Step::Stop => {
later = true;
break;
}
}
}
let again = {
let mut state = self.queue.lock();
if state.again {
state.again = false;
true
} else {
state.running = false;
if !later {
state.failures = 0;
}
false
}
};
if !again {
if later {
self.schedule_replay();
}
return;
}
}
}
/// Runs the replay again after a delay that grows with each run in a row that left
/// actions for later.
fn schedule_replay(self: &Arc<Self>) {
let failures = {
let mut state = self.queue.lock();
state.failures = state.failures.saturating_add(1);
if state.timer {
return;
}
state.timer = true;
state.failures
};
let delay = RETRY_DELAY
.saturating_mul(1 << (failures - 1).min(16))
.min(MAX_RETRY_DELAY);
// Weak: a pending run does not keep a dropped mirror alive.
let inner = Arc::downgrade(self);
let sleep = self.runtime.sleep(delay);
self.runtime.spawn(Box::pin(async move {
sleep.await;
if let Some(inner) = inner.upgrade() {
inner.queue.lock().timer = false;
inner.replay();
}
}));
}
/// The library's connection when its actions can be sent: connected, and its
/// passphrase set if it is encrypted (names are encrypted when sent).
fn ready_api(&self, library: &str) -> Option<LibraryApi> {
let state = self.lock();
let api = state.connection.as_ref()?.apis.get(library)?.clone();
let crypt = state.libraries.iter().find(|l| l.id == library)?.crypt == Some(true);
(!crypt || state.text_keys.contains_key(library)).then_some(api)
}
/// The next actions to send, marked as being sent: the first pending one not
/// `skipped` whose library is ready and that is the oldest of its item, with the
/// next ones of its library that go in the same request (deletions; the same change
/// of other medias). An item's actions go one after the other: one waits while an
/// older one is left for later, or failed until retried or discarded.
async fn next_batch(&self, skipped: &HashSet<i64>) -> Option<(LibraryApi, Vec<QueuedAction>)> {
// Under the copy's write lock: an action discarded or replaced never starts
// while it goes.
let _write = self.viewing.write.lock().await;
// Only the oldest action of an item goes: the others wait for it to be done,
// or discarded.
let pending: Vec<QueuedAction> = {
let state = self.queue.lock();
let mut items = HashSet::new();
(state.actions.iter())
.filter(|a| items.insert((a.library.as_str(), a.action.target())))
.filter(|a| a.status == ActionStatus::Pending && !skipped.contains(&a.id))
.cloned()
.collect()
};
let mut ready: HashMap<String, Option<LibraryApi>> = HashMap::new();
let mut first = None;
for (index, action) in pending.iter().enumerate() {
let api = (ready.entry(action.library.clone()))
.or_insert_with(|| self.ready_api(&action.library))
.clone();
if let Some(api) = api {
first = Some((index, api));
break;
}
}
let (index, api) = first?;
let lead = &pending[index];
let delete = matches!(lead.action, Action::MediaDelete { .. });
let update = lead
.action
.media_update()
.and_then(|u| serde_json::to_value(u).ok());
let mut batch = vec![lead.clone()];
if delete || update.is_some() {
// Each the oldest of its media: no action in between changes it.
for action in pending[index + 1..]
.iter()
.filter(|a| a.library == lead.library)
{
if batch.len() >= BATCH {
break;
}
let same = if delete {
matches!(action.action, Action::MediaDelete { .. })
} else {
action.action.name() == lead.action.name()
&& (action.action.media_update()).and_then(|u| serde_json::to_value(u).ok())
== update
};
if same {
batch.push(action.clone());
}
}
}
let mut state = self.queue.lock();
let ids: HashSet<i64> = batch.iter().map(|a| a.id).collect();
let mut marked = HashSet::new();
for action in state.actions.iter_mut() {
if ids.contains(&action.id) && action.status == ActionStatus::Pending {
action.status = ActionStatus::Sending;
marked.insert(action.id);
}
}
// Discarded or replaced since they were read: not sent.
batch.retain(|a| marked.contains(&a.id));
(!batch.is_empty()).then_some((api, batch))
}
/// Sends a batch and keeps what happened.
async fn attempt(self: &Arc<Self>, api: &LibraryApi, batch: &[QueuedAction]) -> Step {
let library = api.id().to_owned();
let ids: Vec<i64> = batch.iter().map(|a| a.id).collect();
self.emit(MirrorEvent::Actions {
library: library.clone(),
});
// A refresh page read before the server has the change must not undo it.
let viewing = batch[0].action.is_viewing().then(|| self.viewing.begin());
let result = match self.send(api, batch).await {
Err(error) if error.kind() == ErrorKind::NotFound => Ok(Vec::new()),
result => result,
};
let step = match result {
Ok(answers) => match self.sent(&library, &ids, answers).await {
Ok(()) => Step::Next,
Err(_) => {
self.set_pending(&ids, None);
Step::Stop
}
},
Err(error) => {
let failure = failure(&error);
if let Failure::Offline = failure {
self.set_pending(&ids, Some(error.to_string()));
Step::Stop
} else {
let message = error.to_string();
let now = now_ms();
let refused = matches!(failure, Failure::Refused);
let kept = self
.update(|action| {
if !ids.contains(&action.id) {
return false;
}
action.attempts = action.attempts.saturating_add(1);
action.attempted = Some(now);
action.error = Some(message.clone());
action.status = if refused || action.attempts >= MAX_ATTEMPTS {
ActionStatus::Failed
} else {
ActionStatus::Pending
};
true
})
.await;
match kept {
Ok(_) if refused => Step::Next,
Ok(_) => Step::Later,
Err(_) => {
self.set_pending(&ids, None);
Step::Stop
}
}
}
}
};
drop(viewing);
self.emit(MirrorEvent::Actions { library });
step
}
/// Back to pending in memory only: the store has them pending already.
fn set_pending(&self, ids: &[i64], error: Option<String>) {
let mut state = self.queue.lock();
for action in state.actions.iter_mut().filter(|a| ids.contains(&a.id)) {
action.status = ActionStatus::Pending;
if error.is_some() {
action.error = error.clone();
}
}
}
/// Sends a batch ([`Self::next_batch`]): the server's answer for changes of medias.
async fn send(&self, api: &LibraryApi, batch: &[QueuedAction]) -> Result<Vec<Media>> {
let medias = || -> Vec<String> { batch.iter().map(|a| a.action.target().1).collect() };
match &batch[0].action {
Action::MediaDelete { .. } => {
api.remove_medias(&medias()).await?;
}
Action::MediaProgress { media, progress } => {
api.set_media_progress(media, *progress).await?;
}
Action::MovieWatched { movie, date } => {
api.set_movie_watched(movie, date.unwrap_or(0)).await?;
}
Action::MovieProgress { movie, progress } => {
api.set_movie_progress(movie, *progress).await?;
}
Action::EpisodeWatched {
serie,
season,
number,
date,
} => {
(api.set_episode_watched(serie, *season, *number, date.unwrap_or(0))).await?;
}
Action::EpisodeProgress {
serie,
season,
number,
progress,
} => {
(api.set_episode_progress(serie, *season, *number, *progress)).await?;
}
action => {
let mut update = action.media_update().ok_or_else(|| {
Error::transport(format!("cannot send a {} action", action.name()))
})?;
if let Some(name) = update.name.take() {
update.name = Some(self.name_to_send(api, name)?);
}
return api.update_medias(&medias(), &update).await;
}
}
Ok(Vec::new())
}
/// A name as the server keeps it: encrypted with the library's text key in an
/// encrypted library.
fn name_to_send(&self, api: &LibraryApi, name: String) -> Result<String> {
if !api.is_encrypted() {
return Ok(name);
}
let key =
(self.lock().text_keys.get(api.id()).copied()).ok_or(Error::PassphraseRequired)?;
Ok(redseat_crypto::encrypt_text(&key, &name)?)
}
/// Removes actions the server has: the medias it answered are written to the copy
/// (their relations as the copy has them), with the actions still waiting applied.
/// Their newer date keeps an older page of a sync from undoing the change.
async fn sent(&self, library: &str, ids: &[i64], answers: Vec<Media>) -> Result<()> {
let written = {
let _write = self.viewing.write.lock().await;
let mut changes = Changes::default();
if !answers.is_empty() {
let wanted = answers.iter().map(|m| m.id.clone()).collect();
let stored: HashMap<String, MediaItem> = (self
.stored::<MediaItem>(library, SyncKind::Medias, wanted)
.await?
.into_iter())
.map(|media| (media.item.id.clone(), media))
.collect();
// The answer has no relations: the copy's, without what the actions
// still waiting did. A media whose deletion was queued meanwhile is not
// in the copy: the deletion's media stands in, and `rebase` makes the
// answer what discarding the deletion puts back.
for answer in answers {
let media = (stored.get(&answer.id).cloned())
.or_else(|| self.queue.deleted_media(library, &answer.id));
let Some(mut media) = media else {
continue;
};
(self.queue).undo_waiting(library, SyncKind::Medias, &answer.id, ids, |undo| {
undo.undo_media(&mut media)
});
changes.medias.push(MediaItem {
item: answer,
relations: media.relations,
});
}
}
let (mut changed, undos) = self.queue.rebase(library, &mut changes, ids);
let current = self.current(library, &changes, &undos).await?;
changed.extend(self.queue.accept(¤t, undos));
let generation = self.generation(library).await?;
let written = (self.store)
.remove_actions(library, generation, ids.to_vec(), changes)
.await?;
if !changed.is_empty() {
self.store.update_actions(changed).await?;
}
let mut state = self.queue.lock();
// A page read before the server deleted them never writes them again
// (`Queue::drop_deleted`): the action that kept them out is gone.
let deleted: Vec<String> = (state.actions.iter())
.filter(|a| ids.contains(&a.id))
.filter_map(|a| match &a.action {
Action::MediaDelete { media } => Some(media.clone()),
_ => None,
})
.collect();
if !deleted.is_empty() {
drop(self.viewing.begin());
let at = self.viewing.started();
let medias = state.deleted.entry(library.to_owned()).or_default();
medias.extend(deleted.into_iter().map(|media| (media, at)));
}
state.actions.retain(|a| !ids.contains(&a.id));
written
};
self.told(library, written).await
}
}