oxedyne/fe2o3/fe2o3_mail/src/sync/wire.rs
25.0 KiB, 20 runs
created by r1870400018:75209, 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 | //! The JSON wire form of the sync engine's records, written once so the gateway that sends a |
| 2 | //! [`Delta`] and the page that applies it read the same shape (`jdat` feature). |
| 3 | //! |
| 4 | //! ```text |
| 5 | //! Cursor {uid_validity, highest_uid, highest_modseq?, polls, backlog: "1:5", floor} |
| 6 | //! Snapshot {mailbox, cursor?, held?: "1:40,42", window?: "30:42"} |
| 7 | //! Budget {max_count?, max_bytes?, bodies?} |
| 8 | //! Delta {mailbox, tier: "qresync"|"condstore"|"full"|"", reset?: {old, new}, |
| 9 | //! new: [{uid, flags, internal_date, size, raw, whole, arrival, link_mid?, link_gm?}], |
| 10 | //! flags: [{uid, flags}], vanished: "3,7", cursor, more} |
| 11 | //! Entry {id, mailbox, uid_validity, uid, message_id?, size?, internal_date?, year?, |
| 12 | //! action: "flags"|"move"|"archive"|"trash"|"junk"|"not_junk"|"expunge", |
| 13 | //! add?: [..], remove?: [..], to?: "inbox"|"role:<role>"|"path:<name>"} |
| 14 | //! ActReply {id, outcome: "done"|"already"|"gone"|"superseded"|"lost"|"stuck"|"error", |
| 15 | //! detail?} |
| 16 | //! ``` |
| 17 | //! A UID set travels as its IMAP wire form, so 10^5 held UIDs cost bytes. `raw` is standard |
| 18 | //! base64, and may be left out by a reader that keeps the bytes elsewhere (the page hands the |
| 19 | //! delta to its wasm apply without them). An entry's `id` is read as a number or a decimal |
| 20 | //! string (a JavaScript number holds only 53 bits), and its reply's `id` is written back in the |
| 21 | //! same form, so the page matches the two with `===`. A known folder's cursor must carry its |
| 22 | //! `floor`, since a missing one would turn everything left in its backlog into arrivals, and |
| 23 | //! arrivals fire triggers that spend. |
| 24 | //! |
| 25 | //! Decoding is strict where a silent default would lose something: a UID set that does not |
| 26 | //! parse, an unknown action or target, a number out of range or a flag that is not a string is |
| 27 | //! an error naming the field, and a pending entry left out of a rebase would be a press undone. |
| 28 | //! |
| 29 | //! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\ |
| 30 | //! Anthropic Claude |
| 31 | |
| 32 | use crate::sync::{ |
| 33 | ActOutcome, |
| 34 | Action, |
| 35 | Budget, |
| 36 | Cursor, |
| 37 | Delta, |
| 38 | Entry, |
| 39 | FlagState, |
| 40 | LinkKey, |
| 41 | NewMessage, |
| 42 | Reset, |
| 43 | Snapshot, |
| 44 | SpecialUse, |
| 45 | Target, |
| 46 | Tier, |
| 47 | UidSet, |
| 48 | }; |
| 49 | |
| 50 | use oxedyne_fe2o3_core::prelude::*; |
| 51 | use oxedyne_fe2o3_jdat::prelude::*; |
| 52 | use oxedyne_fe2o3_text::base64; |
| 53 | |
| 54 | |
| 55 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 56 | // │ FIELDS │ |
| 57 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 58 | |
| 59 | /// The value under `key`, or `None` when it is absent or `null`. |
| 60 | fn field<'a>(d: &'a Dat, key: &str) -> Option<&'a Dat> { |
| 61 | match d.map_get(&dat!(key)) { |
| 62 | Ok(Some(Dat::Empty)) | Ok(None) | Err(_) => None, |
| 63 | Ok(Some(v)) => Some(v), |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | fn is_map(d: &Dat) -> bool { |
| 68 | matches!(d, Dat::Map(_) | Dat::OrdMap(_)) |
| 69 | } |
| 70 | |
| 71 | /// A whole number under `key` within `0..=max`; absent is 0. |
| 72 | fn whole(d: &Dat, key: &str, max: u64) -> Outcome<u64> { |
| 73 | let v = match field(d, key) { |
| 74 | Some(v) => v, |
| 75 | None => return Ok(0), |
| 76 | }; |
| 77 | match v.get_i64() { |
| 78 | Some(n) if n >= 0 && (n as u64) <= max => Ok(n as u64), |
| 79 | Some(n) => Err(err!("'{}' is {}, outside 0 to {}.", key, n, max; Invalid, Input, Range)), |
| 80 | None => Err(err!("'{}' must be a whole number, not {:?}.", key, v.kind(); Invalid, Input)), |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | fn u32_of(d: &Dat, key: &str) -> Outcome<u32> { |
| 85 | Ok(res!(whole(d, key, u32::MAX as u64)) as u32) |
| 86 | } |
| 87 | |
| 88 | /// A string under `key`; absent is empty. |
| 89 | fn text(d: &Dat, key: &str) -> Outcome<String> { |
| 90 | match field(d, key) { |
| 91 | None => Ok(String::new()), |
| 92 | Some(Dat::Str(s)) => Ok(s.clone()), |
| 93 | Some(v) => Err(err!("'{}' must be a string, not {:?}.", key, v.kind(); Invalid, Input)), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | fn need_text(d: &Dat, key: &str) -> Outcome<String> { |
| 98 | let s = res!(text(d, key)); |
| 99 | if s.is_empty() { |
| 100 | return Err(err!("'{}' is missing.", key; Missing, Input)); |
| 101 | } |
| 102 | Ok(s) |
| 103 | } |
| 104 | |
| 105 | fn boolean(d: &Dat, key: &str) -> Outcome<bool> { |
| 106 | match field(d, key) { |
| 107 | None => Ok(false), |
| 108 | Some(Dat::Bool(b)) => Ok(*b), |
| 109 | Some(v) => Err(err!("'{}' must be true or false, not {:?}.", key, v.kind(); Invalid, Input)), |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// A list of strings under `key`; absent is empty. |
| 114 | fn strings(d: &Dat, key: &str) -> Outcome<Vec<String>> { |
| 115 | match field(d, key) { |
| 116 | None => Ok(Vec::new()), |
| 117 | Some(v) => v.get_string_list().ok_or_else(|| |
| 118 | err!("'{}' must be a list of strings.", key; Invalid, Input)), |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | fn list<'a>(d: &'a Dat, key: &str) -> Outcome<&'a [Dat]> { |
| 123 | match field(d, key) { |
| 124 | None => Ok(&[]), |
| 125 | Some(Dat::List(l)) => Ok(l), |
| 126 | Some(v) => Err(err!("'{}' must be a list, not {:?}.", key, v.kind(); Invalid, Input)), |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | /// A UID set in its IMAP wire form under `key`; absent or empty is the empty set. |
| 131 | fn uid_set(d: &Dat, key: &str) -> Outcome<UidSet> { |
| 132 | let s = res!(text(d, key)); |
| 133 | if s.is_empty() { |
| 134 | return Ok(UidSet::new()); |
| 135 | } |
| 136 | match UidSet::parse(&s) { |
| 137 | Ok(u) => Ok(u), |
| 138 | Err(e) => Err(err!(e, "'{}' is not a UID set: '{}'.", key, s; Invalid, Input)), |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | fn set_dat(s: &UidSet) -> Dat { |
| 143 | dat!(fmt!("{}", s)) |
| 144 | } |
| 145 | |
| 146 | fn strings_dat(f: &[String]) -> Dat { |
| 147 | Dat::List(f.iter().map(|x| dat!(x.clone())).collect()) |
| 148 | } |
| 149 | |
| 150 | fn num_dat(n: u64) -> Dat { |
| 151 | Dat::I64(n as i64) |
| 152 | } |
| 153 | |
| 154 | |
| 155 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 156 | // │ CURSOR, SNAPSHOT, BUDGET │ |
| 157 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 158 | |
| 159 | /// `highest_modseq` of 0 is read as none, which is what a server's 0 means. |
| 160 | pub fn cursor_from(c: &Dat) -> Outcome<Cursor> { |
| 161 | if !is_map(c) { |
| 162 | return Err(err!("A cursor must be an object, not {:?}.", c.kind(); Invalid, Input)); |
| 163 | } |
| 164 | let modseq = res!(whole(c, "highest_modseq", i64::MAX as u64)); |
| 165 | let uv = res!(u32_of(c, "uid_validity")); |
| 166 | if uv != 0 && field(c, "floor").is_none() { |
| 167 | return Err(err!("The cursor of a folder under UIDVALIDITY {} has no 'floor', so what is \ |
| 168 | an arrival cannot be told.", uv; Missing, Input)); |
| 169 | } |
| 170 | Ok(Cursor { |
| 171 | uid_validity: res!(u32_of(c, "uid_validity")), |
| 172 | highest_uid: res!(u32_of(c, "highest_uid")), |
| 173 | highest_modseq: if modseq > 0 { Some(modseq) } else { None }, |
| 174 | polls: res!(u32_of(c, "polls")), |
| 175 | backlog: res!(uid_set(c, "backlog")), |
| 176 | floor: res!(u32_of(c, "floor")), |
| 177 | }) |
| 178 | } |
| 179 | |
| 180 | pub fn cursor_dat(c: &Cursor) -> Dat { |
| 181 | let mut p = vec![ |
| 182 | (dat!("uid_validity"), num_dat(c.uid_validity as u64)), |
| 183 | (dat!("highest_uid"), num_dat(c.highest_uid as u64)), |
| 184 | (dat!("polls"), num_dat(c.polls as u64)), |
| 185 | (dat!("backlog"), set_dat(&c.backlog)), |
| 186 | (dat!("floor"), num_dat(c.floor as u64)), |
| 187 | ]; |
| 188 | if let Some(m) = c.highest_modseq { |
| 189 | p.push((dat!("highest_modseq"), num_dat(m))); |
| 190 | } |
| 191 | create_dat_ordmap(p) |
| 192 | } |
| 193 | |
| 194 | /// A folder as a device holds it; no `cursor` is a folder never synced. |
| 195 | pub fn snapshot_from(f: &Dat) -> Outcome<Snapshot> { |
| 196 | let mailbox = res!(need_text(f, "mailbox")); |
| 197 | let cursor = match field(f, "cursor") { |
| 198 | Some(c) => match cursor_from(c) { |
| 199 | Ok(c) => c, |
| 200 | Err(e) => return Err(err!(e, "The cursor of '{}' cannot be read.", mailbox; Invalid, Input)), |
| 201 | }, |
| 202 | None => Cursor::default(), |
| 203 | }; |
| 204 | let sets = (uid_set(f, "held"), uid_set(f, "window")); |
| 205 | match sets { |
| 206 | (Ok(held), Ok(window)) => Ok(Snapshot { mailbox, cursor, held, window }), |
| 207 | (Err(e), _) | (_, Err(e)) => Err(err!(e, "The folder '{}' cannot be read.", mailbox; Invalid, Input)), |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | pub fn snapshot_dat(s: &Snapshot) -> Dat { |
| 212 | create_dat_ordmap(vec![ |
| 213 | (dat!("mailbox"), dat!(s.mailbox.clone())), |
| 214 | (dat!("cursor"), cursor_dat(&s.cursor)), |
| 215 | (dat!("held"), set_dat(&s.held)), |
| 216 | (dat!("window"), set_dat(&s.window)), |
| 217 | ]) |
| 218 | } |
| 219 | |
| 220 | /// The budget a request asks for, within `limit`: its count and bytes may only lower the limit's, |
| 221 | /// and `bodies` is the request's alone. `None` is the limit without bodies. |
| 222 | pub fn budget_within(b: Option<&Dat>, limit: &Budget) -> Outcome<Budget> { |
| 223 | let b = match b { |
| 224 | Some(b) if is_map(b) => b, |
| 225 | Some(Dat::Empty) | None => return Ok(Budget { bodies: false, ..*limit }), |
| 226 | Some(v) => return Err(err!("'budget' must be an object, not {:?}.", v.kind(); Invalid, Input)), |
| 227 | }; |
| 228 | let count = res!(whole(b, "max_count", u32::MAX as u64)) as usize; |
| 229 | let bytes = res!(whole(b, "max_bytes", i64::MAX as u64)); |
| 230 | Ok(Budget { |
| 231 | max_count: if count > 0 { count.min(limit.max_count) } else { limit.max_count }, |
| 232 | max_bytes: if bytes > 0 { bytes.min(limit.max_bytes) } else { limit.max_bytes }, |
| 233 | bodies: res!(boolean(b, "bodies")), |
| 234 | ..*limit |
| 235 | }) |
| 236 | } |
| 237 | |
| 238 | pub fn budget_dat(b: &Budget) -> Dat { |
| 239 | create_dat_ordmap(vec![ |
| 240 | (dat!("max_count"), num_dat(b.max_count as u64)), |
| 241 | (dat!("max_bytes"), num_dat(b.max_bytes)), |
| 242 | (dat!("bodies"), Dat::Bool(b.bodies)), |
| 243 | ]) |
| 244 | } |
| 245 | |
| 246 | |
| 247 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 248 | // │ DELTA │ |
| 249 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 250 | |
| 251 | fn tier_word(t: Option<Tier>) -> &'static str { |
| 252 | match t { |
| 253 | Some(Tier::QResync) => "qresync", |
| 254 | Some(Tier::CondStore) => "condstore", |
| 255 | Some(Tier::Full) => "full", |
| 256 | None => "", |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | fn tier_of(w: &str) -> Outcome<Option<Tier>> { |
| 261 | Ok(match w { |
| 262 | "qresync" => Some(Tier::QResync), |
| 263 | "condstore" => Some(Tier::CondStore), |
| 264 | "full" => Some(Tier::Full), |
| 265 | "" => None, |
| 266 | other => return Err(err!("Unknown tier '{}'.", other; Invalid, Input)), |
| 267 | }) |
| 268 | } |
| 269 | |
| 270 | fn new_from(m: &Dat) -> Outcome<NewMessage> { |
| 271 | let uid = res!(u32_of(m, "uid")); |
| 272 | if uid == 0 { |
| 273 | return Err(err!("A new message needs its 'uid'."; Missing, Input)); |
| 274 | } |
| 275 | let raw = res!(text(m, "raw")); |
| 276 | let raw = match base64::decode(&raw) { |
| 277 | Ok(r) => r, |
| 278 | Err(e) => return Err(err!(e, "The 'raw' of UID {} is not base64.", uid; Invalid, Input)), |
| 279 | }; |
| 280 | let gm = res!(text(m, "link_gm")); |
| 281 | let mid = res!(text(m, "link_mid")); |
| 282 | let link = if !gm.is_empty() { |
| 283 | match gm.parse::<u64>() { |
| 284 | Ok(n) => Some(LinkKey::GmMsgId(n)), |
| 285 | Err(_) => return Err(err!("The 'link_gm' of UID {} is not a number: '{}'.", |
| 286 | uid, gm; Invalid, Input)), |
| 287 | } |
| 288 | } else if !mid.is_empty() { |
| 289 | Some(LinkKey::MessageId(mid)) |
| 290 | } else { |
| 291 | None |
| 292 | }; |
| 293 | Ok(NewMessage { |
| 294 | uid, |
| 295 | flags: res!(strings(m, "flags")), |
| 296 | internal_date: res!(text(m, "internal_date")), |
| 297 | size: res!(u32_of(m, "size")), |
| 298 | raw, |
| 299 | whole: res!(boolean(m, "whole")), |
| 300 | link, |
| 301 | arrival: res!(boolean(m, "arrival")), |
| 302 | }) |
| 303 | } |
| 304 | |
| 305 | fn new_dat(m: &NewMessage) -> Dat { |
| 306 | let mut p = vec![ |
| 307 | (dat!("uid"), num_dat(m.uid as u64)), |
| 308 | (dat!("flags"), strings_dat(&m.flags)), |
| 309 | (dat!("internal_date"), dat!(m.internal_date.clone())), |
| 310 | (dat!("size"), num_dat(m.size as u64)), |
| 311 | (dat!("raw"), dat!(base64::encode(&m.raw))), |
| 312 | (dat!("whole"), Dat::Bool(m.whole)), |
| 313 | (dat!("arrival"), Dat::Bool(m.arrival)), |
| 314 | ]; |
| 315 | match &m.link { |
| 316 | Some(LinkKey::MessageId(s)) => p.push((dat!("link_mid"), dat!(s.clone()))), |
| 317 | Some(LinkKey::GmMsgId(n)) => p.push((dat!("link_gm"), dat!(fmt!("{}", n)))), |
| 318 | None => (), |
| 319 | } |
| 320 | create_dat_ordmap(p) |
| 321 | } |
| 322 | |
| 323 | fn delta_body(d: &Dat, mailbox: String) -> Outcome<Delta> { |
| 324 | let cursor = match field(d, "cursor") { |
| 325 | Some(c) => res!(cursor_from(c)), |
| 326 | None => return Err(err!("The delta has no cursor."; Missing, Input)), |
| 327 | }; |
| 328 | if cursor.uid_validity == 0 { |
| 329 | return Err(err!("The delta's cursor has no UIDVALIDITY."; Missing, Input)); |
| 330 | } |
| 331 | let reset = match field(d, "reset") { |
| 332 | Some(r) if is_map(r) => Some(Reset { |
| 333 | old: res!(u32_of(r, "old")), |
| 334 | new: res!(u32_of(r, "new")), |
| 335 | }), |
| 336 | Some(v) => return Err(err!("'reset' must be an object, not {:?}.", v.kind(); Invalid, Input)), |
| 337 | None => None, |
| 338 | }; |
| 339 | let mut new = Vec::new(); |
| 340 | for m in res!(list(d, "new")) { |
| 341 | new.push(res!(new_from(m))); |
| 342 | } |
| 343 | let mut flags = Vec::new(); |
| 344 | for f in res!(list(d, "flags")) { |
| 345 | flags.push(FlagState { |
| 346 | uid: res!(u32_of(f, "uid")), |
| 347 | flags: res!(strings(f, "flags")), |
| 348 | }); |
| 349 | } |
| 350 | Ok(Delta { |
| 351 | mailbox, |
| 352 | tier: res!(tier_of(&res!(text(d, "tier")))), |
| 353 | reset, |
| 354 | new, |
| 355 | flags, |
| 356 | vanished: res!(uid_set(d, "vanished")), |
| 357 | cursor, |
| 358 | more: res!(boolean(d, "more")), |
| 359 | }) |
| 360 | } |
| 361 | |
| 362 | /// One folder's delta. A delta that carries an `error` in place of its changes (the gateway's |
| 363 | /// answer for a folder the server refused) is an error here, with that message. |
| 364 | pub fn delta_from(d: &Dat) -> Outcome<Delta> { |
| 365 | let mailbox = res!(need_text(d, "mailbox")); |
| 366 | let refused = res!(text(d, "error")); |
| 367 | if !refused.is_empty() { |
| 368 | return Err(err!("The folder '{}' was not synced: {}", mailbox, refused; Input)); |
| 369 | } |
| 370 | match delta_body(d, mailbox.clone()) { |
| 371 | Ok(x) => Ok(x), |
| 372 | Err(e) => Err(err!(e, "The delta for '{}' cannot be read.", mailbox; Invalid, Input)), |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | pub fn delta_dat(d: &Delta) -> Dat { |
| 377 | let mut p = vec![ |
| 378 | (dat!("mailbox"), dat!(d.mailbox.clone())), |
| 379 | (dat!("tier"), dat!(tier_word(d.tier))), |
| 380 | ]; |
| 381 | if let Some(r) = d.reset { |
| 382 | p.push((dat!("reset"), create_dat_ordmap(vec![ |
| 383 | (dat!("old"), num_dat(r.old as u64)), |
| 384 | (dat!("new"), num_dat(r.new as u64)), |
| 385 | ]))); |
| 386 | } |
| 387 | let flags = d.flags.iter().map(|f| create_dat_ordmap(vec![ |
| 388 | (dat!("uid"), num_dat(f.uid as u64)), |
| 389 | (dat!("flags"), strings_dat(&f.flags)), |
| 390 | ])).collect(); |
| 391 | p.extend(vec![ |
| 392 | (dat!("new"), Dat::List(d.new.iter().map(new_dat).collect())), |
| 393 | (dat!("flags"), Dat::List(flags)), |
| 394 | (dat!("vanished"), set_dat(&d.vanished)), |
| 395 | (dat!("cursor"), cursor_dat(&d.cursor)), |
| 396 | (dat!("more"), Dat::Bool(d.more)), |
| 397 | ]); |
| 398 | create_dat_ordmap(p) |
| 399 | } |
| 400 | |
| 401 | /// The place of a folder that could not be synced, in a response's `deltas`. |
| 402 | pub fn refused_dat(mailbox: &str, why: &str) -> Dat { |
| 403 | create_dat_ordmap(vec![ |
| 404 | (dat!("mailbox"), dat!(mailbox.to_string())), |
| 405 | (dat!("error"), dat!(why.to_string())), |
| 406 | ]) |
| 407 | } |
| 408 | |
| 409 | |
| 410 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 411 | // │ ENTRY AND REPLY │ |
| 412 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 413 | |
| 414 | fn role_word(r: SpecialUse) -> &'static str { |
| 415 | match r { |
| 416 | SpecialUse::Sent => "sent", |
| 417 | SpecialUse::Drafts => "drafts", |
| 418 | SpecialUse::Trash => "trash", |
| 419 | SpecialUse::Junk => "junk", |
| 420 | SpecialUse::Archive => "archive", |
| 421 | SpecialUse::All => "all", |
| 422 | SpecialUse::Flagged => "flagged", |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | /// `inbox`, `role:<role>` or `path:<name>`; a role an action cannot target is none. |
| 427 | pub fn target_of(to: &str) -> Option<Target> { |
| 428 | if to.eq_ignore_ascii_case("inbox") { |
| 429 | return Some(Target::Inbox); |
| 430 | } |
| 431 | if let Some(p) = to.strip_prefix("path:") { |
| 432 | return if p.is_empty() { None } else { Some(Target::Path(p.to_string())) }; |
| 433 | } |
| 434 | let role = match to.strip_prefix("role:") { |
| 435 | Some(r) => r, |
| 436 | None => return None, |
| 437 | }; |
| 438 | let r = match role { |
| 439 | "sent" => SpecialUse::Sent, |
| 440 | "drafts" => SpecialUse::Drafts, |
| 441 | "trash" => SpecialUse::Trash, |
| 442 | "junk" => SpecialUse::Junk, |
| 443 | "archive" => SpecialUse::Archive, |
| 444 | "all" => SpecialUse::All, |
| 445 | "flagged" => SpecialUse::Flagged, |
| 446 | _ => return None, |
| 447 | }; |
| 448 | Some(Target::Role(r)) |
| 449 | } |
| 450 | |
| 451 | pub fn target_word(t: &Target) -> String { |
| 452 | match t { |
| 453 | Target::Inbox => fmt!("inbox"), |
| 454 | Target::Path(p) => fmt!("path:{}", p), |
| 455 | Target::Role(r) => fmt!("role:{}", role_word(*r)), |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | /// The JSON type an entry's `id` came in, which its reply's `id` is written back in. |
| 460 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 461 | pub enum IdForm { |
| 462 | #[default] |
| 463 | Number, // a JSON number |
| 464 | Text, // a decimal string |
| 465 | } |
| 466 | |
| 467 | pub fn id_form(e: &Dat) -> IdForm { |
| 468 | match field(e, "id") { |
| 469 | Some(Dat::Str(_)) => IdForm::Text, |
| 470 | _ => IdForm::Number, |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | /// An entry's `id`, as a number or a decimal string. |
| 475 | fn entry_id(e: &Dat) -> Outcome<u64> { |
| 476 | match field(e, "id") { |
| 477 | Some(Dat::Str(s)) => s.parse::<u64>().map_err(|_| |
| 478 | err!("The entry id '{}' is not a number.", s; Invalid, Input)), |
| 479 | Some(v) => match v.get_i64() { |
| 480 | Some(n) if n >= 0 => Ok(n as u64), |
| 481 | _ => Err(err!("The entry id must be a whole number."; Invalid, Input)), |
| 482 | }, |
| 483 | None => Err(err!("An entry needs its 'id'."; Missing, Input)), |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | fn entry_body(e: &Dat, id: u64) -> Outcome<Entry> { |
| 488 | let mailbox = res!(need_text(e, "mailbox")); |
| 489 | let uid = res!(u32_of(e, "uid")); |
| 490 | let uid_validity = res!(u32_of(e, "uid_validity")); |
| 491 | if uid == 0 || uid_validity == 0 { |
| 492 | return Err(err!("It needs its 'uid' and 'uid_validity'."; Missing, Input)); |
| 493 | } |
| 494 | let action = match res!(text(e, "action")).as_str() { |
| 495 | "flags" => { |
| 496 | let (add, remove) = (res!(strings(e, "add")), res!(strings(e, "remove"))); |
| 497 | if add.is_empty() && remove.is_empty() { |
| 498 | return Err(err!("It changes no flag."; Missing, Input)); |
| 499 | } |
| 500 | Action::Flags { add, remove } |
| 501 | } |
| 502 | w @ ("move" | "copy") => { |
| 503 | let to = res!(text(e, "to")); |
| 504 | let to = res!(target_of(&to).ok_or_else(|| err!( |
| 505 | "It goes to '{}': 'to' must be inbox, role:<role> or path:<name>.", to; Invalid, Input))); |
| 506 | if w == "move" { Action::Move { to } } else { Action::Copy { to } } |
| 507 | } |
| 508 | "archive" => Action::Archive, |
| 509 | "trash" => Action::Trash, |
| 510 | "junk" => Action::Junk, |
| 511 | "not_junk" => Action::NotJunk, |
| 512 | "expunge" => Action::Expunge, |
| 513 | other => return Err(err!("Its action '{}' is unknown.", other; Invalid, Input)), |
| 514 | }; |
| 515 | let year = res!(whole(e, "year", u16::MAX as u64)) as u16; |
| 516 | Ok(Entry { |
| 517 | id, |
| 518 | mailbox, |
| 519 | uid_validity, |
| 520 | uid, |
| 521 | message_id: res!(text(e, "message_id")), |
| 522 | size: res!(u32_of(e, "size")), |
| 523 | internal_date: res!(text(e, "internal_date")), |
| 524 | year: if year > 0 { Some(year) } else { None }, |
| 525 | action, |
| 526 | }) |
| 527 | } |
| 528 | |
| 529 | /// One journal entry. It is all or nothing: an entry that cannot be read is never run or rebased |
| 530 | /// in part. |
| 531 | pub fn entry_from(e: &Dat) -> Outcome<Entry> { |
| 532 | let id = res!(entry_id(e)); |
| 533 | match entry_body(e, id) { |
| 534 | Ok(x) => Ok(x), |
| 535 | Err(x) => Err(err!(x, "Entry {} cannot be read.", id; Invalid, Input)), |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | pub fn entry_dat(e: &Entry) -> Dat { |
| 540 | let mut p = vec![ |
| 541 | (dat!("id"), num_dat(e.id)), |
| 542 | (dat!("mailbox"), dat!(e.mailbox.clone())), |
| 543 | (dat!("uid_validity"), num_dat(e.uid_validity as u64)), |
| 544 | (dat!("uid"), num_dat(e.uid as u64)), |
| 545 | ]; |
| 546 | if !e.message_id.is_empty() { |
| 547 | p.push((dat!("message_id"), dat!(e.message_id.clone()))); |
| 548 | } |
| 549 | p.push((dat!("size"), num_dat(e.size as u64))); |
| 550 | if !e.internal_date.is_empty() { |
| 551 | p.push((dat!("internal_date"), dat!(e.internal_date.clone()))); |
| 552 | } |
| 553 | if let Some(y) = e.year { |
| 554 | p.push((dat!("year"), num_dat(y as u64))); |
| 555 | } |
| 556 | let word = match &e.action { |
| 557 | Action::Flags { add, remove } => { |
| 558 | p.push((dat!("add"), strings_dat(add))); |
| 559 | p.push((dat!("remove"), strings_dat(remove))); |
| 560 | "flags" |
| 561 | } |
| 562 | Action::Move { to } => { |
| 563 | p.push((dat!("to"), dat!(target_word(to)))); |
| 564 | "move" |
| 565 | } |
| 566 | Action::Copy { to } => { |
| 567 | p.push((dat!("to"), dat!(target_word(to)))); |
| 568 | "copy" |
| 569 | } |
| 570 | Action::Archive => "archive", |
| 571 | Action::Trash => "trash", |
| 572 | Action::Junk => "junk", |
| 573 | Action::NotJunk => "not_junk", |
| 574 | Action::Expunge => "expunge", |
| 575 | }; |
| 576 | p.push((dat!("action"), dat!(word))); |
| 577 | create_dat_ordmap(p) |
| 578 | } |
| 579 | |
| 580 | /// What became of one entry: a definite outcome, or `Err` with why it could not be run, so it is |
| 581 | /// kept and sent again. |
| 582 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 583 | pub struct ActReply { |
| 584 | pub id: u64, |
| 585 | pub form: IdForm, // the entry's, so the page's `===` matches |
| 586 | pub outcome: std::result::Result<ActOutcome, String>, |
| 587 | } |
| 588 | |
| 589 | pub fn reply_dat(r: &ActReply) -> Dat { |
| 590 | let (word, detail) = match &r.outcome { |
| 591 | Ok(ActOutcome::Done) => ("done", None), |
| 592 | Ok(ActOutcome::Already(at)) => ("already", Some(at)), |
| 593 | Ok(ActOutcome::Gone) => ("gone", None), |
| 594 | Ok(ActOutcome::Superseded(at)) => ("superseded", Some(at)), |
| 595 | Ok(ActOutcome::Lost) => ("lost", None), |
| 596 | Ok(ActOutcome::Stuck(why)) => ("stuck", Some(why)), |
| 597 | Err(why) => ("error", Some(why)), |
| 598 | }; |
| 599 | let mut p = vec![ |
| 600 | (dat!("id"), match r.form { |
| 601 | IdForm::Number => num_dat(r.id), |
| 602 | IdForm::Text => dat!(fmt!("{}", r.id)), |
| 603 | }), |
| 604 | (dat!("outcome"), dat!(word)), |
| 605 | ]; |
| 606 | if let Some(d) = detail { |
| 607 | p.push((dat!("detail"), dat!(d.clone()))); |
| 608 | } |
| 609 | create_dat_ordmap(p) |
| 610 | } |
| 611 | |
| 612 | pub fn reply_from(d: &Dat) -> Outcome<ActReply> { |
| 613 | let id = res!(entry_id(d)); |
| 614 | let detail = res!(text(d, "detail")); |
| 615 | let outcome = match res!(text(d, "outcome")).as_str() { |
| 616 | "done" => Ok(ActOutcome::Done), |
| 617 | "already" => Ok(ActOutcome::Already(detail)), |
| 618 | "gone" => Ok(ActOutcome::Gone), |
| 619 | "superseded" => Ok(ActOutcome::Superseded(detail)), |
| 620 | "lost" => Ok(ActOutcome::Lost), |
| 621 | "stuck" => Ok(ActOutcome::Stuck(detail)), |
| 622 | "error" => Err(detail), |
| 623 | other => return Err(err!("The outcome '{}' of entry {} is unknown.", |
| 624 | other, id; Invalid, Input)), |
| 625 | }; |
| 626 | Ok(ActReply { id, form: id_form(d), outcome }) |
| 627 | } |
| 628 | |
| 629 | |
| 630 | // ┌───────────────────────────────────────────────────────────────────────────┐ |
| 631 | // │ THE JDAT TRAITS │ |
| 632 | // └───────────────────────────────────────────────────────────────────────────┘ |
| 633 | |
| 634 | macro_rules! wire_traits { |
| 635 | ($t:ty, $from:ident, $to:expr) => { |
| 636 | impl ToDat for $t { |
| 637 | fn to_dat(&self) -> Outcome<Dat> { |
| 638 | Ok($to(self)) |
| 639 | } |
| 640 | } |
| 641 | impl FromDat for $t { |
| 642 | fn from_dat(dat: Dat) -> Outcome<Self> { |
| 643 | $from(&dat) |
| 644 | } |
| 645 | } |
| 646 | }; |
| 647 | } |
| 648 | |
| 649 | wire_traits!(Cursor, cursor_from, cursor_dat); |
| 650 | wire_traits!(Snapshot, snapshot_from, snapshot_dat); |
| 651 | wire_traits!(Delta, delta_from, delta_dat); |
| 652 | wire_traits!(Entry, entry_from, entry_dat); |
| 653 | wire_traits!(ActReply, reply_from, reply_dat); |