Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_mail/src/sync/apply.rs

6.9 KiB, 1 run

created by r1870400018:75203, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Applying a [`Delta`] to a device's cache, over a [`SyncStore`] (OPFS in a browser, a directory
2//! natively).
3//!
4//! Every message is held under its (uidvalidity, uid) [`MsgKey`], which is also its Maildir
5//! name, so a delta applied twice -- after a crash before its cursor was stored -- puts nothing
6//! twice and changes nothing the second time. The cursor is stored last, once every write has
7//! landed.
8
9use crate::sync::{
10 act::{
11 Action,
12 Entry,
13 },
14 Delta,
15 Cursor,
16};
17
18use oxedyne_fe2o3_core::prelude::*;
19
20
21/// A held message's identity: unique per folder, and never reused within a generation.
22#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
23pub struct MsgKey {
24 pub uid_validity: u32,
25 pub uid: u32,
26}
27
28/// A device's cache of its folders. One generation per folder is current, and at most one older
29/// generation is set aside while a reset rebuilds.
30pub trait SyncStore {
31 /// The UIDVALIDITY of the current generation, `None` for a folder never synced.
32 fn generation(&self, mailbox: &str) -> Outcome<Option<u32>>;
33 /// Sets the current generation aside (dropping any older one set aside before it) and starts
34 /// an empty one under `uid_validity`.
35 fn begin_generation(&mut self, mailbox: &str, uid_validity: u32) -> Outcome<()>;
36 /// Drops the generation set aside; nothing where there is none.
37 fn end_generation(&mut self, mailbox: &str) -> Outcome<()>;
38 fn flags(&self, mailbox: &str, key: MsgKey) -> Outcome<Option<Vec<String>>>;
39 /// Holds a message, or replaces a header-only copy with a whole one. Was anything written?
40 fn put(&mut self, mailbox: &str, key: MsgKey, flags: &[String], raw: &[u8], whole: bool)
41 -> Outcome<bool>;
42 fn change_flags(&mut self, mailbox: &str, key: MsgKey, add: &[String], remove: &[String])
43 -> Outcome<()>;
44 /// Was it held?
45 fn remove(&mut self, mailbox: &str, key: MsgKey) -> Outcome<bool>;
46 fn cursor(&self, mailbox: &str) -> Outcome<Option<Cursor>>;
47 fn set_cursor(&mut self, mailbox: &str, cursor: &Cursor) -> Outcome<()>;
48}
49
50/// What one apply changed; all zero for a replay.
51#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
52pub struct Applied {
53 pub added: usize,
54 pub changed: usize,
55 pub removed: usize,
56 pub reset: bool,
57}
58
59/// Applies `d` to `store`, rebased under the device's `pending` journal: a flag that a pending
60/// entry has changed keeps its local value, and a message a pending entry has moved away is
61/// left alone, until that entry's outcome arrives. A delta never undoes a press just made.
62pub fn apply<T: SyncStore>(store: &mut T, d: &Delta, pending: &[Entry]) -> Outcome<Applied> {
63 let mb = d.mailbox.as_str();
64 let uv = d.cursor.uid_validity;
65 let mut out = Applied::default();
66 let held = res!(store.generation(mb));
67 if held != Some(uv) {
68 // A reset, or the first sync. A delta for an older generation than the one held, which
69 // only a stale replay could carry, must not be mixed into it.
70 match (held, d.reset) {
71 (None, _) => (),
72 (Some(h), Some(r)) if h == r.old => out.reset = true,
73 (Some(h), _) => return Err(err!(
74 "The delta for {} is for UIDVALIDITY {}, and the device holds {}: it is not \
75 applied.", mb, uv, h; Mismatch, Input)),
76 }
77 res!(store.begin_generation(mb, uv));
78 }
79
80 let mine: Vec<&Entry> = pending.iter()
81 .filter(|e| e.mailbox == d.mailbox && e.uid_validity == uv)
82 .collect();
83 let moved = |uid: u32| mine.iter().any(|e| e.uid == uid && e.action.removes());
84
85 for m in &d.new {
86 if moved(m.uid) {
87 continue;
88 }
89 let flags = rebase_flags(&m.flags, m.uid, &mine);
90 let key = MsgKey { uid_validity: uv, uid: m.uid };
91 if res!(store.put(mb, key, &flags, &m.raw, m.whole)) {
92 out.added += 1;
93 }
94 }
95 for f in &d.flags {
96 if moved(f.uid) {
97 continue;
98 }
99 let key = MsgKey { uid_validity: uv, uid: f.uid };
100 let local = match res!(store.flags(mb, key)) {
101 Some(l) => l,
102 None => continue,
103 };
104 let want = rebase_flags(&f.flags, f.uid, &mine);
105 let add: Vec<String> = want.iter().filter(|w| !has_flag(&local, w)).cloned().collect();
106 let remove: Vec<String> = local.iter().filter(|l| !has_flag(&want, l)).cloned().collect();
107 if !add.is_empty() || !remove.is_empty() {
108 res!(store.change_flags(mb, key, &add, &remove));
109 out.changed += 1;
110 }
111 }
112 for uid in d.vanished.iter() {
113 if res!(store.remove(mb, MsgKey { uid_validity: uv, uid })) {
114 out.removed += 1;
115 }
116 }
117 if !d.more {
118 res!(store.end_generation(mb));
119 }
120 res!(store.set_cursor(mb, &d.cursor));
121 Ok(out)
122}
123
124/// The server's `flags` for `uid` with every pending flag change for it laid over them, in
125/// journal order.
126pub fn rebase_flags(flags: &[String], uid: u32, pending: &[&Entry]) -> Vec<String> {
127 let mut out: Vec<String> = flags.to_vec();
128 for e in pending.iter().filter(|e| e.uid == uid) {
129 if let Action::Flags { add, remove } = &e.action {
130 out.retain(|f| !has_flag(remove, f));
131 for a in add {
132 if !has_flag(&out, a) {
133 out.push(a.clone());
134 }
135 }
136 }
137 }
138 out
139}
140
141/// Flags compare without regard to case (RFC 3501 2.3.2).
142fn has_flag(set: &[String], f: &str) -> bool {
143 set.iter().any(|s| s.eq_ignore_ascii_case(f))
144}
145
146
147// ── Maildir names ───────────────────────────────────────────────────
148
149/// The system flags a Maildir name carries in its `:2,` info, in the ASCII order it requires.
150const INFO: [(char, &str); 5] = [
151 ('D', "\\Draft"),
152 ('F', "\\Flagged"),
153 ('R', "\\Answered"),
154 ('S', "\\Seen"),
155 ('T', "\\Deleted"),
156];
157
158/// `<uidvalidity>.<uid>:2,<info>`: the key is the unique part, so a renamed flag change and a
159/// replayed put land on the same file.
160pub fn maildir_name(key: MsgKey, flags: &[String]) -> String {
161 let info: String = INFO.iter()
162 .filter(|(_, f)| has_flag(flags, f))
163 .map(|(c, _)| *c)
164 .collect();
165 fmt!("{}.{}:2,{}", key.uid_validity, key.uid, info)
166}
167
168/// The key and system flags of a name [`maildir_name`] wrote; `None` for any other name.
169pub fn parse_maildir_name(name: &str) -> Option<(MsgKey, Vec<String>)> {
170 let (base, info) = name.split_once(":2,")?;
171 let (uv, uid) = base.split_once('.')?;
172 let key = MsgKey {
173 uid_validity: uv.parse().ok()?,
174 uid: uid.parse().ok()?,
175 };
176 let flags = INFO.iter()
177 .filter(|(c, _)| info.contains(*c))
178 .map(|(_, f)| f.to_string())
179 .collect();
180 Some((key, flags))
181}