diff --git a/crates/engine/src/conversations.rs b/crates/engine/src/conversations.rs index 83c0cea58..cd30bb0ce 100644 --- a/crates/engine/src/conversations.rs +++ b/crates/engine/src/conversations.rs @@ -14,27 +14,117 @@ //! is the same, and only one that isn't has its hash worked out again, and is pointed at as it is //! now, so that it isn't hashed again at the next check and what it was is let go of. So a flag, //! a category, a move or a read mark keeps the conversations (a pass of pointer comparisons over -//! a few hundred chunks, and over the messages of the few that changed), and a changed subject or -//! header, a server's answer about its conversation, or a message more or less, has them worked -//! out again. +//! a few hundred chunks, and over the messages of the few that changed). A changed subject or +//! header, a server's answer about its conversation, or a message more or less has only its +//! topics worked out again (#1897): a conversation is of one account and one topic +//! ([`ThreadIndex::rejoin`]), and with each message is kept its topic, and with each topic its +//! messages. So a new account's first download, a piece at a time, doesn't go over every message +//! of the mailbox at each piece. A change past [`most_changed`] (another mailbox opened in its +//! place) has them worked out over every message. +//! +//! That first build, at opening, is shared out among threads ([`kept_on`]): the chunks first, +//! each message's topic and hash; then the topics, in parts by their hash, each joined into its +//! conversations ([`Joined`]); then the index, in parts by message id +//! ([`ThreadIndex::of_joined`]). Where no thread can be started (the browser), it is all done +//! on this one. //! //! The check is made at the first ask after a command begins and after it ends. Within one //! command, an ask, then a change of what groups a message, then another ask would get the first //! answer: no command does that (each works out the conversation it acts on before it changes //! anything), and one that would must call [`Session::threads_may_change`] between the two. -use std::collections::hash_map::DefaultHasher; -use std::hash::{Hash, Hasher}; -use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::collections::hash_map::RandomState; +use std::collections::{HashMap, HashSet}; +use std::hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak}; use mailcraft_model::messages::Chunk; -use mailcraft_model::{Id, Mailbox, Message, ThreadIndex, ThreadKey}; +use mailcraft_model::{Id, Joined, Mailbox, Message, ThreadIndex, ThreadKey}; use crate::Session; /// The conversations kept ([`Session::threads`]). pub(crate) type ThreadsCache = Mutex>; +/// A topic of an account ([`Message::topic_key`]), as a hash of it keyed for this run (subjects +/// are anybody's, so no sender can make them collide on purpose). Two topics may still share +/// one: the messages of a hash are put by their topic itself before they are joined. +type Topic = u64; + +/// The hash of the topic `key` of `account` ([`Topic`]). +fn topic_hash(account: Id, key: &str) -> Topic { + static KEYS: OnceLock = OnceLock::new(); + KEYS.get_or_init(RandomState::new).hash_one((account, key)) +} + +/// A hasher for what is already a keyed hash ([`Topic`]): it is only spread again, since the +/// parts of the topics each have the same top bits ([`share_of`]). +#[derive(Default)] +struct Hashed(u64); + +impl Hasher for Hashed { + fn finish(&self) -> u64 { + self.0.wrapping_mul(0x9e37_79b9_7f4a_7c15) + } + + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.0 = self.0.rotate_left(8) ^ u64::from(*b); + } + } + + fn write_u64(&mut self, n: u64) { + self.0 = n; + } +} + +/// How many parts the topics are kept in, each of those whose hash falls in it: the parts are +/// worked out on threads of their own at the first build. +const TOPIC_SHARES: usize = 16; + +/// Which part of the topics `topic` falls in. +fn share_of(topic: Topic) -> usize { + usize::try_from(topic >> 60).unwrap_or(0) % TOPIC_SHARES +} + +/// The ids of the messages of each topic, smallest first, in [`TOPIC_SHARES`] parts. +#[derive(Default)] +struct Topics(Vec, BuildHasherDefault>>); + +impl Topics { + fn get(&self, topic: &Topic) -> Option<&Vec> { + self.0.get(share_of(*topic)).and_then(|share| share.get(topic)) + } + + fn get_mut(&mut self, topic: &Topic) -> Option<&mut Vec> { + self.0.get_mut(share_of(*topic)).and_then(|share| share.get_mut(topic)) + } + + /// The ids of `topic`, which it is given when it has none. + fn insert_id(&mut self, topic: Topic, id: Id) { + if self.0.is_empty() { + self.0 = (0..TOPIC_SHARES).map(|_| HashMap::default()).collect(); + } + if let Some(share) = self.0.get_mut(share_of(topic)) { + let ids = share.entry(topic).or_default(); + if let Err(at) = ids.binary_search(&id) { + ids.insert(at, id); + } + } + } + + /// Forget those of `topics` left without a message. + fn drop_empty<'a>(&mut self, topics: impl IntoIterator) { + for topic in topics { + if let Some(share) = self.0.get_mut(share_of(*topic)) + && share.get(topic).is_some_and(Vec::is_empty) + { + share.remove(topic); + } + } + } +} + pub(crate) struct Kept { /// The revision and the count of messages they were last checked at; `None` once the mailbox /// may have changed since ([`Session::threads_may_change`]). @@ -42,28 +132,63 @@ pub(crate) struct Kept { threads: Arc, /// Of each chunk of the map of messages, in the map's order. seen: Vec, - /// How many messages were hashed again in checks (for tests). + /// The ids of the messages of each topic, smallest first: the topics a change touches are + /// worked out again, and only those (#1897). + topics: Topics, + /// How many messages the checks hashed again (for tests). rehashed: u64, + /// How many times they were worked out over every message (for tests). + built: u64, } /// What is kept of one chunk of the map of messages: the chunk as it was seen, and of each of -/// its messages, in order of id, its id, a weak pointer to it and the hash of what groups it. +/// its messages, in order of id, what was seen of it. struct SeenChunk { key: Id, chunk: Weak, - messages: Vec<(Id, Weak, u64)>, + messages: Vec, +} + +/// What was seen of one message: a weak pointer to it, the hash of what groups it, and its topic +/// (none, without a subject: a conversation of its own). +struct Seen { + id: Id, + message: Weak, + hash: u64, + topic: Option, } -impl SeenChunk { - fn of(key: Id, chunk: &Arc) -> SeenChunk { - let messages = chunk.iter().map(|(id, m)| (*id, Arc::downgrade(m), grouping_hash(m))).collect(); - SeenChunk { key, chunk: Arc::downgrade(chunk), messages } +/// A hasher for [`grouping_hash`], eight bytes at a step: it only tells a message that changed +/// from one that didn't, so it needn't be one a sender can't make collide (the default one isn't +/// keyed there either), and it is asked of every message at the first build. +#[derive(Default)] +struct Changed(u64); + +impl Hasher for Changed { + fn finish(&self) -> u64 { + self.0 + } + + fn write(&mut self, bytes: &[u8]) { + let (words, rest) = bytes.as_chunks::<8>(); + for word in words { + self.write_u64(u64::from_le_bytes(*word)); + } + let mut last = [0u8; 8]; + if let Some(to) = last.get_mut(..rest.len()) { + to.copy_from_slice(rest); + } + self.write_u64(u64::from_le_bytes(last) ^ (rest.len() as u64) << 59); + } + + fn write_u64(&mut self, n: u64) { + self.0 = (self.0.rotate_left(26) ^ n).wrapping_mul(0x9e37_79b9_7f4a_7c15); } } /// The hash of what [`ThreadIndex::build`] reads of `m`. fn grouping_hash(m: &Message) -> u64 { - let mut h = DefaultHasher::new(); + let mut h = Changed::default(); let server = m.server.as_ref().map(|s| (s.thread.as_str(), s.thread_asked)); (m.account, &m.subject, &m.message_id, &m.in_reply_to, &m.references, server).hash(&mut h); m.answers.as_ref().map(|a| (a.forward, &a.message_id)).hash(&mut h); @@ -84,49 +209,283 @@ pub(crate) fn same_grouping(a: &Message, b: &Message) -> bool { && server(a) == server(b) } -/// Whether `kept` is of the messages of `mailbox`, as far as conversations go; a chunk or a -/// message found the same is pointed at as it is now. -fn still_of(kept: &mut Kept, mailbox: &Mailbox) -> bool { - let chunks = mailbox.messages.chunks(); - if kept.seen.len() != chunks.len() { - return false; +fn seen(id: Id, m: &Arc) -> Seen { + let key = m.topic_key(); + let topic = (!key.is_empty()).then(|| topic_hash(m.account, &key)); + Seen { id, message: Arc::downgrade(m), hash: grouping_hash(m), topic } +} + +/// The messages `same`, all of one [`Topic`] and in order of id, put by their topic itself (of +/// which there is one, unless two topics share the hash), each in order of id. +fn by_topic<'a>(same: Vec<(&'a Message, String)>, into: &mut Vec>) { + let Some((first, rest)) = same.split_first() else { return }; + if rest.iter().all(|(m, key)| m.account == first.0.account && *key == first.1) { + into.push(same.into_iter().map(|(m, _)| m).collect()); + return; } - let mut rehashed = 0u64; - let same = kept.seen.iter_mut().zip(chunks).all(|(seen, (key, chunk))| { - if seen.key != *key { - return false; + let mut put: HashMap<(Id, String), Vec<&Message>> = HashMap::new(); + for (m, key) in same { + put.entry((m.account, key)).or_default().push(m); + } + into.extend(put.into_values()); +} + +/// Most threads the first build goes over the chunks on. +const MOST_THREADS: usize = 16; + +/// How many threads to work out `mailbox`'s conversations on: one for a small one. +fn threads_for(mailbox: &Mailbox) -> usize { + std::thread::available_parallelism().map_or(1, |p| p.get()).min(MOST_THREADS).min(mailbox.messages.chunks().len() / 16).max(1) +} + +/// One message as the first build sees it: its topic's hash, itself, and its topic. +type Entry<'a> = (Topic, &'a Message, String); + +/// `work` done for each of `items`, each on a thread of its own and the last on this one, in +/// their order. An item whose thread can't be started is worked on this one (it is handed to its +/// thread only once the thread runs, so it comes back when it doesn't); `None` when a thread +/// gave no answer, its item then lost, for the caller to do it all again on one. +fn on_threads(items: Vec, work: impl Fn(T) -> R + Sync) -> Option> { + let work = &work; + std::thread::scope(|scope| { + let mut items = items; + let last = items.pop(); + let started: Vec> = items + .into_iter() + .map(|item| { + let (give, take) = std::sync::mpsc::sync_channel::(1); + let thread = std::thread::Builder::new().name("conversations".into()).spawn_scoped(scope, move || take.recv().ok().map(work)); + match thread { + Ok(thread) => give.send(item).map(|()| thread).map_err(|back| back.0), + Err(_) => Err(item), + } + }) + .collect(); + let mine = last.map(work); + let mut done = Vec::with_capacity(started.len().saturating_add(1)); + for started in started { + done.push(match started { + Ok(thread) => thread.join().ok().flatten()?, + Err(item) => work(item), + }); } - if std::ptr::eq(seen.chunk.as_ptr(), Arc::as_ptr(chunk)) { - return true; + done.extend(mine); + Some(done) + }) +} + +/// What is seen of the chunks `chunks`, and every message of them that has a topic, put into +/// the parts of the topics ([`TOPIC_SHARES`]) by its topic. +fn seen_chunks<'a>(chunks: &[(&Id, &'a Arc)]) -> (Vec, Vec>>) { + let mut seen = Vec::with_capacity(chunks.len()); + let each = chunks.iter().map(|(_, c)| c.len()).sum::() / TOPIC_SHARES + 16; + let mut entries: Vec> = (0..TOPIC_SHARES).map(|_| Vec::with_capacity(each)).collect(); + for (key, chunk) in chunks { + let mut messages = Vec::with_capacity(chunk.len()); + for (id, m) in chunk.iter() { + let name = m.topic_key(); + let topic = (!name.is_empty()).then(|| topic_hash(m.account, &name)); + if let Some(topic) = topic + && let Some(share) = entries.get_mut(share_of(topic)) + { + share.push((topic, m.as_ref(), name)); + } + messages.push(Seen { id: *id, message: Arc::downgrade(m), hash: grouping_hash(m), topic }); } - if seen.messages.len() != chunk.len() { - return false; + seen.push(SeenChunk { key: **key, chunk: Arc::downgrade(chunk), messages }); + } + (seen, entries) +} + +/// The topics of one part, of the messages `parts` (each in order of id, one part after the +/// other), and the conversations of each topic of more than one. +fn topics_of(parts: Vec>) -> (HashMap, BuildHasherDefault>, Joined) { + let mut entries = Vec::with_capacity(parts.iter().map(Vec::len).sum()); + for part in parts { + entries.extend(part); + } + // By topic; within one, in order of id, as they came (a stable sort). + entries.sort_by_key(|(topic, _, _)| *topic); + let mut topics = HashMap::with_capacity_and_hasher(entries.len(), BuildHasherDefault::default()); + let mut lists = Vec::new(); + let mut entries = entries.into_iter().peekable(); + while let Some((topic, m, name)) = entries.next() { + let mut same = vec![(m, name)]; + while let Some((_, m, name)) = entries.next_if(|(next, _, _)| *next == topic) { + same.push((m, name)); + } + topics.insert(topic, same.iter().map(|(m, _)| m.id).collect()); + if same.len() > 1 { + by_topic(same, &mut lists); + } + } + let joined = Joined::of_topics(lists.iter().map(Vec::as_slice)); + (topics, joined) +} + +/// What is kept of `mailbox`, with its conversations worked out over every message. +fn kept_of(mailbox: &Mailbox, at: Option<(u64, usize)>, built: u64) -> Kept { + kept_on(mailbox, at, built, threads_for(mailbox)) +} + +/// [`kept_of`], worked out on `threads` threads: the chunks shared out among them, then the +/// parts of the topics. +fn kept_on(mailbox: &Mailbox, at: Option<(u64, usize)>, built: u64, threads: usize) -> Kept { + let threads = threads.clamp(1, TOPIC_SHARES); + match worked_on(mailbox, threads) { + Some((seen, topics, threads)) => Kept { at, threads: Arc::new(threads), seen, topics, rehashed: 0, built: built.saturating_add(1) }, + // A thread gave no answer: all again, on this one (where nothing is left to a thread). + None => { + let (seen, topics, threads) = worked_on(mailbox, 1).unwrap_or_default(); + Kept { at, threads: Arc::new(threads), seen, topics, rehashed: 0, built: built.saturating_add(1) } } - let same = seen.messages.iter_mut().zip(chunk.iter()).all(|((was_id, was, hash), (id, now))| { - if was_id != id { - return false; + } +} + +/// What [`kept_on`] keeps, worked out on `threads` threads; `None` when one of them gave no +/// answer. +fn worked_on(mailbox: &Mailbox, threads: usize) -> Option<(Vec, Topics, ThreadIndex)> { + let chunks: Vec<(&Id, &Arc)> = mailbox.messages.chunks().iter().collect(); + let share = chunks.len().div_ceil(threads).max(1); + let parts = on_threads(chunks.chunks(share).collect(), seen_chunks)?; + let mut seen = Vec::with_capacity(chunks.len()); + // Of each part of the topics, its messages of each share of the chunks. + let mut shares: Vec>> = (0..TOPIC_SHARES).map(|_| Vec::new()).collect(); + for (part, of_it) in parts { + seen.extend(part); + for (share, entries) in shares.iter_mut().zip(of_it) { + share.push(entries); + } + } + // The parts of the topics, a few to each thread. + let mut each: Vec>)>> = (0..threads).map(|_| Vec::new()).collect(); + for (at, share) in shares.into_iter().enumerate() { + if let Some(to) = each.get_mut(at % threads) { + to.push((at, share)); + } + } + let worked = on_threads(each, |of_it| of_it.into_iter().map(|(at, share)| (at, topics_of(share))).collect::>())?; + let mut topics: Vec<(usize, HashMap, BuildHasherDefault>)> = Vec::with_capacity(TOPIC_SHARES); + let mut joined = Vec::new(); + for (at, (of_share, of_it)) in worked.into_iter().flatten() { + topics.push((at, of_share)); + joined.push(of_it); + } + topics.sort_by_key(|(at, _)| *at); + let topics = Topics(topics.into_iter().map(|(_, share)| share).collect()); + Some((seen, topics, ThreadIndex::of_joined(joined, threads))) +} + +/// Most messages a change may touch for its topics alone to be worked out again: past it (a +/// mailbox opened in place of another, a whole folder brought in at once) working them all out +/// is no slower. +fn most_changed(mailbox: &Mailbox) -> usize { + (mailbox.messages.len() / 4).max(1024) +} + +/// Bring `kept` in step with `mailbox`: a chunk that is the same `Arc` holds the same messages +/// and isn't looked into; in one that isn't, a message that is the same `Arc` is the same, and +/// only one that isn't has its hash worked out again, and is pointed at as it is now. The topics +/// of the messages that came, went or group otherwise are worked out again. Whether it could be +/// (`false` past [`most_changed`]: `kept` is then to be built afresh), and whether anything about +/// the conversations changed. +fn bring_in_step(kept: &mut Kept, mailbox: &Mailbox) -> Option { + let most = most_changed(mailbox); + let mut gone: Vec<(Id, Topic)> = Vec::new(); + let mut came: Vec<(Id, Topic)> = Vec::new(); + let mut changed = 0usize; + let mut rehashed = 0u64; + let mut old = std::mem::take(&mut kept.seen).into_iter().peekable(); + let mut now_seen = Vec::with_capacity(mailbox.messages.chunks().len()); + let went = |was: Seen, gone: &mut Vec<(Id, Topic)>, changed: &mut usize| { + *changed = changed.saturating_add(1); + if let Some(topic) = was.topic { + gone.push((was.id, topic)); + } + }; + for (key, chunk) in mailbox.messages.chunks() { + while let Some(before) = old.next_if(|c| c.key < *key) { + for was in before.messages { + went(was, &mut gone, &mut changed); + } + } + let before = old.next_if(|c| c.key == *key); + let before = match before { + Some(same) if std::ptr::eq(same.chunk.as_ptr(), Arc::as_ptr(chunk)) => { + now_seen.push(same); + continue; + } + other => other, + }; + let mut was = before.map(|c| c.messages).unwrap_or_default().into_iter().peekable(); + let mut messages = Vec::with_capacity(chunk.len()); + for (id, now) in chunk.iter() { + while let Some(left) = was.next_if(|w| w.id < *id) { + went(left, &mut gone, &mut changed); } - if std::ptr::eq(was.as_ptr(), Arc::as_ptr(now)) { - return true; + match was.next_if(|w| w.id == *id) { + Some(same) if std::ptr::eq(same.message.as_ptr(), Arc::as_ptr(now)) => messages.push(same), + Some(same) => { + rehashed = rehashed.saturating_add(1); + let hash = grouping_hash(now); + if hash == same.hash { + messages.push(Seen { message: Arc::downgrade(now), ..same }); + } else { + went(same, &mut gone, &mut changed); + let one = seen(*id, now); + came.extend(one.topic.map(|topic| (*id, topic))); + messages.push(one); + } + } + None => { + changed = changed.saturating_add(1); + let one = seen(*id, now); + came.extend(one.topic.map(|topic| (*id, topic))); + messages.push(one); + } } - rehashed = rehashed.saturating_add(1); - let same = grouping_hash(now) == *hash; - if same { - *was = Arc::downgrade(now); + if changed > most { + return None; } - same - }); - if same { - seen.chunk = Arc::downgrade(chunk); } - same - }); + for left in was { + went(left, &mut gone, &mut changed); + } + now_seen.push(SeenChunk { key: *key, chunk: Arc::downgrade(chunk), messages }); + } + for before in old { + for was in before.messages { + went(was, &mut gone, &mut changed); + } + } + if changed > most { + return None; + } + kept.seen = now_seen; kept.rehashed = kept.rehashed.saturating_add(rehashed); - same -} - -fn seen_of(mailbox: &Mailbox) -> Vec { - mailbox.messages.chunks().iter().map(|(key, chunk)| SeenChunk::of(*key, chunk)).collect() + if gone.is_empty() && came.is_empty() { + return Some(false); + } + // The topics touched, and every id they had. + let touched: HashSet = gone.iter().chain(&came).map(|(_, topic)| *topic).collect(); + let was: Vec = touched.iter().filter_map(|topic| kept.topics.get(topic)).flatten().copied().collect(); + for (id, topic) in gone { + if let Some(ids) = kept.topics.get_mut(&topic) + && let Ok(at) = ids.binary_search(&id) + { + ids.remove(at); + } + } + for (id, topic) in came { + kept.topics.insert_id(topic, id); + } + kept.topics.drop_empty(&touched); + let mut topics: Vec> = Vec::new(); + for ids in touched.iter().filter_map(|topic| kept.topics.get(topic)) { + by_topic(ids.iter().filter_map(|id| mailbox.message(*id)).map(|m| (m, m.topic_key())).collect(), &mut topics); + } + Arc::make_mut(&mut kept.threads).rejoin(&was, &topics); + Some(true) } impl Session { @@ -140,17 +499,20 @@ impl Session { pub fn threads(&self) -> Arc { let key = self.threads_key(); let mut cache = self.threads_cache.lock().unwrap_or_else(PoisonError::into_inner); + let mut built = 0; if let Some(kept) = cache.as_mut() { if kept.at == Some(key) { return kept.threads.clone(); } - if still_of(kept, &self.mailbox) { + if bring_in_step(kept, &self.mailbox).is_some() { kept.at = Some(key); return kept.threads.clone(); } + built = kept.built; } - let threads = Arc::new(ThreadIndex::build(self.mailbox.messages.values().map(|m| m.as_ref()))); - *cache = Some(Kept { at: Some(key), threads: threads.clone(), seen: seen_of(&self.mailbox), rehashed: 0 }); + let kept = kept_of(&self.mailbox, Some(key), built); + let threads = kept.threads.clone(); + *cache = Some(kept); threads } @@ -187,7 +549,18 @@ impl Session { /// Whether the conversations of `before` are those of `after`, as [`Session::threads`] checks. #[cfg(test)] pub(crate) fn grouping_kept(before: &Mailbox, after: &Mailbox) -> bool { - still_of(&mut Kept { at: None, threads: Arc::default(), seen: seen_of(before), rehashed: 0 }, after) + bring_in_step(&mut kept_of(before, None, 0), after) == Some(false) +} + +/// The conversations of `after`, worked out on `threads` threads over `before` and then brought +/// in step with `after` (or worked out afresh over it, past [`most_changed`]). +#[cfg(test)] +pub(crate) fn threads_on(before: &Mailbox, after: &Mailbox, threads: usize) -> Arc { + let mut kept = kept_on(before, None, 0, threads); + if bring_in_step(&mut kept, after).is_none() { + kept = kept_on(after, None, 0, threads); + } + kept.threads } #[cfg(test)] @@ -202,8 +575,13 @@ impl Session { && kept.seen.iter().zip(chunks).all(|(seen, (_, chunk))| { std::ptr::eq(seen.chunk.as_ptr(), Arc::as_ptr(chunk)) && seen.messages.len() == chunk.len() - && seen.messages.iter().zip(chunk.iter()).all(|((_, was, _), (_, now))| std::ptr::eq(was.as_ptr(), Arc::as_ptr(now))) + && seen.messages.iter().zip(chunk.iter()).all(|(was, (_, now))| std::ptr::eq(was.message.as_ptr(), Arc::as_ptr(now))) }); (kept.rehashed, current) } + + /// How many times the conversations were worked out over every message (#1897). + pub(crate) fn threads_built(&self) -> u64 { + self.threads_cache.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map_or(0, |kept| kept.built) + } } diff --git a/crates/engine/src/conversations_tests.rs b/crates/engine/src/conversations_tests.rs new file mode 100644 index 000000000..594e71397 --- /dev/null +++ b/crates/engine/src/conversations_tests.rs @@ -0,0 +1,285 @@ +// SPDX-FileCopyrightText: MailCraft contributors +// SPDX-License-Identifier: MIT OR Apache-2.0 +//! #1897: the conversations kept are brought in step with a change by working out again only +//! the topics it touched, and they come out as a build over every message does. + +use mailcraft_model::sync::ServerMessage; +use mailcraft_model::{FolderKind, Id, Mailbox, Message, ThreadIndex}; +use proptest::prelude::*; + +use crate::Session; + +const SUBJECTS: [&str; 5] = ["Invoice for October", "RE: Invoice for October", "Plans", "Fw: plans", ""]; + +/// A change to the mailbox, by a message's place among those there are (wrapped around). +#[derive(Clone, Debug)] +enum Change { + Add { other: bool, subject: usize, own: u8, answers: Option, thread: Option }, + Remove(usize), + Subject(usize, usize), + Answers(usize, Option), + Thread(usize, Option), + Read(usize), +} + +fn change() -> impl Strategy { + let id = || prop::option::of(0u8..12); + prop_oneof![ + 4 => (any::(), 0..SUBJECTS.len(), 0u8..12, id(), id()) + .prop_map(|(other, subject, own, answers, thread)| Change::Add { other, subject, own, answers, thread }), + 2 => any::().prop_map(Change::Remove), + 1 => (any::(), 0..SUBJECTS.len()).prop_map(|(at, subject)| Change::Subject(at, subject)), + 1 => (any::(), id()).prop_map(|(at, answers)| Change::Answers(at, answers)), + 1 => (any::(), id()).prop_map(|(at, thread)| Change::Thread(at, thread)), + 1 => any::().prop_map(Change::Read), + ] +} + +fn message_id(n: u8) -> String { + format!("m{n}@example.org") +} + +/// Two accounts, and enough messages in them to fill more than one chunk of the map of messages. +fn mailbox() -> (Session, [Id; 2]) { + let mut s = Session::new(Mailbox::with_local_account("Avery", "avery@example.org")); + let other = s.run("account.add", &serde_json::json!({"email": "avery@mail.example", "incoming": {"host": "imap.mail.example"}})).unwrap(); + let other = other["id"].as_u64().unwrap(); + let first = s.mailbox.accounts[0].id; + let inboxes = [s.mailbox.folder_of_kind(first, FolderKind::Inbox).unwrap(), s.mailbox.folder_of_kind(other, FolderKind::Inbox).unwrap()]; + for n in 0..1_100u32 { + let m = Message { + folder: inboxes[(n % 2) as usize], + subject: format!("Topic {}", n % 40), + message_id: format!("base{n}@example.org"), + in_reply_to: if n % 3 == 0 { format!("base{}@example.org", n.saturating_sub(40)) } else { String::new() }, + ..Default::default() + }; + s.mailbox.add_message(m).unwrap(); + } + s.mailbox_changed(); + (s, inboxes) +} + +fn pick(s: &Session, at: usize) -> Option { + let ids: Vec = s.mailbox.messages.keys().copied().collect(); + ids.get(at % ids.len().max(1)).copied() +} + +fn apply(s: &mut Session, inboxes: [Id; 2], change: &Change) { + let mb = &mut s.mailbox; + match change { + Change::Add { other, subject, own, answers, thread } => { + let m = Message { + folder: inboxes[usize::from(*other)], + subject: SUBJECTS[*subject].into(), + message_id: message_id(*own), + in_reply_to: answers.map(message_id).unwrap_or_default(), + server: thread.map(|t| ServerMessage { thread: format!("AAQkconv{t}"), ..Default::default() }), + ..Default::default() + }; + mb.add_message(m).unwrap(); + } + Change::Remove(at) => { + if let Some(id) = pick(s, *at) { + s.mailbox.remove_message(id).unwrap(); + } + } + Change::Subject(at, subject) => { + if let Some(id) = pick(s, *at) { + s.mailbox.message_mut(id).unwrap().subject = SUBJECTS[*subject].into(); + } + } + Change::Answers(at, answers) => { + if let Some(id) = pick(s, *at) { + s.mailbox.message_mut(id).unwrap().in_reply_to = answers.map(message_id).unwrap_or_default(); + } + } + Change::Thread(at, thread) => { + if let Some(id) = pick(s, *at) { + s.mailbox.message_mut(id).unwrap().server = thread.map(|t| ServerMessage { thread: format!("AAQkconv{t}"), ..Default::default() }); + } + } + Change::Read(at) => { + if let Some(id) = pick(s, *at) { + let m = s.mailbox.message_mut(id).unwrap(); + m.read = !m.read; + } + } + } + s.mailbox_changed(); +} + +/// Every message's conversation, as `threads` has it. +fn conversations(s: &Session, threads: &ThreadIndex) -> Vec<(Id, Id, Vec)> { + s.mailbox.messages.keys().map(|id| (*id, threads.key(*id).0, threads.members(*id))).collect() +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })] + + #[test] + fn conversations_brought_in_step_are_those_built_afresh(changes in prop::collection::vec(change(), 1..40), every in 1usize..6) { + let (mut s, inboxes) = mailbox(); + let start = s.mailbox.clone(); + let _ = s.threads(); + for (n, change) in changes.iter().enumerate() { + apply(&mut s, inboxes, change); + // Asked after some of the changes, not each: several come together, as a frame takes + // in several pieces. + if n % every == 0 { + let kept = s.threads(); + let afresh = ThreadIndex::build(s.mailbox.messages.values().map(|m| m.as_ref())); + prop_assert_eq!(conversations(&s, &kept), conversations(&s, &afresh), "after {:?}", &changes[..=n]); + } + } + let kept = s.threads(); + let afresh = ThreadIndex::build(s.mailbox.messages.values().map(|m| m.as_ref())); + prop_assert_eq!(conversations(&s, &kept), conversations(&s, &afresh)); + // Brought in step each time: built over every message only once. + prop_assert_eq!(s.threads_built(), 1); + // Worked out on several threads, at first and brought in step since, they are the same. + for threads in [2, 3, 16] { + let on = crate::conversations::threads_on(&s.mailbox, &s.mailbox, threads); + prop_assert_eq!(conversations(&s, &on), conversations(&s, &afresh), "built on {} threads", threads); + let on = crate::conversations::threads_on(&start, &s.mailbox, threads); + prop_assert_eq!(conversations(&s, &on), conversations(&s, &afresh), "built on {} threads, then in step", threads); + } + } +} + +/// New mail of one account, a piece at a time, doesn't have every message of the mailbox worked +/// out again: only its topics are (#1897). +#[test] +fn new_mail_works_out_its_own_topics_only() { + let (mut s, inboxes) = mailbox(); + let _ = s.threads(); + for n in 0..200u8 { + apply(&mut s, inboxes, &Change::Add { other: true, subject: usize::from(n % 4), own: n % 12, answers: Some(n % 7), thread: None }); + let _ = s.threads(); + } + assert_eq!(s.threads_built(), 1); + // A mailbox opened in place of this one is worked out afresh. + let mut other = s.mailbox.clone(); + for id in other.messages.keys().copied().collect::>() { + other.message_mut(id).unwrap().subject = "Everything".into(); + } + s.mailbox = other; + s.mailbox_changed(); + let threads = s.threads(); + assert_eq!(s.threads_built(), 2); + let afresh = ThreadIndex::build(s.mailbox.messages.values().map(|m| m.as_ref())); + assert_eq!(conversations(&s, &threads), conversations(&s, &afresh)); +} + +/// How long the conversations take to work out over a large mailbox of real conversations: of +/// one to eight messages each, replies naming what they answer, and every twentieth conversation +/// of a topic many share ("Weekly report"). `MAILCRAFT_CONVERSATIONS_BENCH_MESSAGES` makes it +/// another size than 326,000. Run with `--release --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: builds a mailbox of 326,000 messages in memory"] +fn conversations_bench() { + let messages: u32 = std::env::var("MAILCRAFT_CONVERSATIONS_BENCH_MESSAGES").ok().and_then(|s| s.parse().ok()).unwrap_or(326_000); + let (mut s, inboxes) = mailbox(); + let mut n = 0u32; + let mut conversation = 0u32; + while n < messages { + let size = 1 + conversation % 8; + let topic = if conversation.is_multiple_of(20) { "Weekly report".to_string() } else { format!("Plans for the harbour, part {conversation}") }; + let mut references: Vec = Vec::new(); + for k in 0..size { + let id = format!("c{conversation}.{k}@example.org"); + let m = Message { + folder: inboxes[(conversation % 2) as usize], + subject: if k == 0 { topic.clone() } else { format!("Re: {topic}") }, + message_id: format!("<{id}>"), + in_reply_to: references.last().cloned().unwrap_or_default(), + references: references.clone(), + ..Default::default() + }; + s.mailbox.add_message(m).unwrap(); + references.push(format!("<{id}>")); + n += 1; + } + conversation += 1; + } + s.mailbox_changed(); + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + let mut built = Vec::new(); + let mut afresh = Vec::new(); + for _ in 0..15 { + let t = std::time::Instant::now(); + let threads = ThreadIndex::build(s.mailbox.messages.values().map(|m| m.as_ref())); + afresh.push(ms(t.elapsed())); + drop(threads); + let fresh = Session::new(s.mailbox.clone()); + let t = std::time::Instant::now(); + let _ = fresh.threads(); + built.push(ms(t.elapsed())); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let cores = std::thread::available_parallelism().map_or(1, |p| p.get()); + eprintln!( + "CONVERSATIONS_BENCH {} messages, {cores} cores: ThreadIndex::build median {:.1} ms {afresh:.0?}; first build median {:.1} ms {built:.0?}", + s.mailbox.messages.len(), + median(&mut afresh), + median(&mut built) + ); + let _ = s.threads(); + let mut pieces = Vec::new(); + for p in 0..20u32 { + for k in 0..50u32 { + let m = Message { + folder: inboxes[1], + subject: format!("Re: Plans for the harbour, part {}", p * 50 + k), + message_id: format!(""), + in_reply_to: format!("", p * 50 + k), + ..Default::default() + }; + s.mailbox.add_message(m).unwrap(); + } + s.mailbox_changed(); + let t = std::time::Instant::now(); + let _ = s.threads(); + pieces.push(ms(t.elapsed())); + } + eprintln!("CONVERSATIONS_BENCH a piece of 50 new messages brought in step: median {:.1} ms {pieces:.1?}", median(&mut pieces)); + assert_eq!(s.threads_built(), 1); +} + +/// Worked out on threads over a mailbox of many chunks, then brought in step with changes, the +/// conversations are those of a build over every message on one. +#[test] +fn conversations_worked_out_on_threads_are_those_built_on_one() { + let (mut s, inboxes) = mailbox(); + for n in 0..6_000u32 { + let m = Message { + folder: inboxes[(n % 2) as usize], + subject: if n % 3 == 0 { format!("Topic {}", n % 70) } else { format!("Re: Topic {}", n % 70) }, + message_id: format!("more{n}@example.org"), + in_reply_to: if n % 4 == 0 { format!("more{}@example.org", n.saturating_sub(70)) } else { String::new() }, + ..Default::default() + }; + s.mailbox.add_message(m).unwrap(); + } + s.mailbox_changed(); + let start = s.mailbox.clone(); + for n in 0..60u8 { + let change = match n % 4 { + 0 => Change::Add { other: n % 8 == 0, subject: usize::from(n % 5), own: n % 12, answers: Some(n % 7), thread: None }, + 1 => Change::Remove(usize::from(n) * 97), + 2 => Change::Subject(usize::from(n) * 131, usize::from(n % 5)), + _ => Change::Answers(usize::from(n) * 59, Some(n % 12)), + }; + apply(&mut s, inboxes, &change); + } + let afresh = ThreadIndex::build(s.mailbox.messages.values().map(|m| m.as_ref())); + for threads in [1, 2, 3, 4, 7] { + let on = crate::conversations::threads_on(&s.mailbox, &s.mailbox, threads); + assert_eq!(conversations(&s, &on), conversations(&s, &afresh), "built on {threads} threads"); + let on = crate::conversations::threads_on(&start, &s.mailbox, threads); + assert_eq!(conversations(&s, &on), conversations(&s, &afresh), "built on {threads} threads, then in step"); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e04b09331..4941f4948 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -437,6 +437,8 @@ mod category_rows_tests; #[cfg(test)] mod composing_tests; #[cfg(test)] +mod conversations_tests; +#[cfg(test)] mod counts_tests; #[cfg(test)] mod draft_in_thread_tests; diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index a17237573..3892a6900 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -113,7 +113,7 @@ pub use rule::{ pub use senders::{MAX_SENDER_ADDRESSES, SenderAddress, SenderProblem, clean_sender_addresses}; pub use signature::Signature; pub use task::{LocalTasks, MAX_TASK_GONE, SharedTaskList, SharedTaskLists, Task, TaskFields, TaskGone, TaskPatch}; -pub use thread_index::{ThreadIndex, ThreadKey}; +pub use thread_index::{Joined, ThreadIndex, ThreadKey}; /// An item's identity inside one mailbox. 0 means "not assigned yet". pub type Id = u64; diff --git a/crates/model/src/message.rs b/crates/model/src/message.rs index aa594759d..02065e1e7 100644 --- a/crates/model/src/message.rs +++ b/crates/model/src/message.rs @@ -728,7 +728,9 @@ impl Message { /// the same topic are of one conversation only when they are linked too /// ([`crate::ThreadIndex`], #795). pub fn topic_key(&self) -> String { - self.topic().to_lowercase() + // Without the copy `topic` makes: it is asked of every message when the conversations + // are worked out (#1897). + topic_of(&self.subject).to_lowercase() } /// Its size as the message list shows and sorts it (#273, #300): an IMAP message too large to diff --git a/crates/model/src/thread_index.rs b/crates/model/src/thread_index.rs index a4091adba..1b8e8083d 100644 --- a/crates/model/src/thread_index.rs +++ b/crates/model/src/thread_index.rs @@ -33,6 +33,7 @@ //! topic joined by a union-find over a map from each id to the first message that named it. use std::collections::HashMap; +use std::hash::{BuildHasherDefault, Hasher}; use crate::sync::thread_id; use crate::{Id, Message}; @@ -48,14 +49,77 @@ pub const MAX_LINK_ID: usize = 998; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ThreadKey(pub Id); -/// The conversations of a set of messages ([`ThreadIndex::build`]). +/// A hasher for message ids, which the mailbox gives out and no sender chooses: a multiply that +/// spreads them over the table, much cheaper than the default one, which is for keys from +/// outside. +#[derive(Default)] +pub struct IdHasher(u64); + +impl Hasher for IdHasher { + fn finish(&self) -> u64 { + self.0 + } + + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.write_u64(u64::from(*b)); + } + } + + fn write_u64(&mut self, n: u64) { + self.0 = (self.0.rotate_left(5) ^ n).wrapping_mul(0x9e37_79b9_7f4a_7c15); + } +} + +type ById = HashMap>; + +/// How many parts an index is kept in, each of the messages whose ids fall in it ([`shard_of`]): +/// so that the parts of a large one can be filled on threads of their own +/// ([`ThreadIndex::of_joined`]). +const SHARDS: usize = 16; + +/// The part of an index the message `id` falls in. +fn shard_of(id: Id) -> usize { + usize::try_from(id.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 60).unwrap_or(0) % SHARDS +} + +/// One part of an index ([`SHARDS`]). #[derive(Clone, Debug, Default)] -pub struct ThreadIndex { +struct Shard { /// The key of each message of a conversation of more than one; one that isn't here is /// its own. - keys: HashMap, - /// The messages of each conversation of more than one, by id. - members: HashMap>, + keys: ById, + /// The messages of each conversation of more than one, by the id of its key. + members: ById>, +} + +impl Shard { + /// The part `at` of the index of the conversations `groups` (each smallest first): its keys + /// of the messages that fall in it, and its conversations `own`, those whose key falls in it. + fn of(at: usize, groups: &[Vec>], own: Vec>) -> Shard { + let ids = groups.iter().flatten().map(Vec::len).sum::(); + let mut keys = ById::with_capacity_and_hasher(ids / SHARDS + ids / (SHARDS * 8), BuildHasherDefault::default()); + for ids in groups.iter().flatten() { + let Some(key) = ids.first().copied().map(ThreadKey) else { continue }; + for id in ids.iter().filter(|id| shard_of(**id) == at) { + keys.insert(*id, key); + } + } + let mut members = ById::with_capacity_and_hasher(own.len(), BuildHasherDefault::default()); + for ids in own { + if let Some(key) = ids.first().copied() { + members.insert(key, ids); + } + } + Shard { keys, members } + } +} + +/// The conversations of a set of messages ([`ThreadIndex::build`]). +#[derive(Clone, Debug, Default)] +pub struct ThreadIndex { + /// Its parts ([`SHARDS`] of them, or none while it holds nothing). + shards: Vec, /// Steps taken building it: for the tests that hold it to linear work. work: u64, } @@ -143,30 +207,51 @@ impl Sets { } } -impl ThreadIndex { - /// The conversations of `messages`: those of one account and one topic, linked as the - /// module's documentation says. - pub fn build<'a>(messages: impl IntoIterator) -> ThreadIndex { - let mut index = ThreadIndex::default(); - let mut topics: HashMap<(Id, String), Vec<&Message>> = HashMap::new(); - for m in messages { - index.work = index.work.saturating_add(1); - let topic = m.topic_key(); - if !topic.is_empty() { - topics.entry((m.account, topic)).or_default().push(m); +/// The conversations of more than one message of one topic ([`Joined::of`]), worked out apart +/// from an index: for the topics of a mailbox worked out on several threads, then taken in +/// ([`ThreadIndex::take_in`]). +#[derive(Debug, Default)] +pub struct Joined { + /// The messages of each, smallest first. + groups: Vec>, + work: u64, +} + +impl Joined { + /// The conversations of `same`, messages all of one account and one topic, in order of id. + pub fn of(same: &[&Message]) -> Joined { + Joined::of_topics([same]) + } + + /// The conversations of each of `topics` ([`Joined::of`]), together. + pub fn of_topics<'a>(topics: impl IntoIterator) -> Joined { + let mut joined = Joined::default(); + // Kept from one topic to the next, as long as they stay small. + let mut named: HashMap<&str, usize> = HashMap::new(); + let mut threads: HashMap = HashMap::new(); + let mut by_set: Vec<(usize, Id)> = Vec::new(); + for same in topics { + if same.len() < 2 { + continue; } + joined.join(same, &mut named, &mut threads, &mut by_set); + if named.capacity() > 4096 { + named = HashMap::new(); + } + named.clear(); + threads.clear(); } - for same in topics.into_values().filter(|same| same.len() > 1) { - index.join(&same); - } - index + joined } - /// Link the messages `same`, all of one account and one topic, into their conversations. - fn join(&mut self, same: &[&Message]) { + fn join<'a>( + &mut self, + same: &[&'a Message], + named: &mut HashMap<&'a str, usize>, + threads: &mut HashMap, + by_set: &mut Vec<(usize, Id)>, + ) { let mut sets = Sets::new(same.len()); - let mut named: HashMap<&str, usize> = HashMap::new(); - let mut threads: HashMap = HashMap::new(); for (i, m) in same.iter().enumerate() { for id in links(m) { self.work = self.work.saturating_add(1); @@ -191,38 +276,163 @@ impl ThreadIndex { // Then the unknowns, among themselves, and only those still linked to nothing: one that a // reply names is of that reply's conversation, and joining it to the other unknowns would // join two threads through it (#795). - let alone: Vec = (0..same.len()).filter(|&i| same.get(i).is_some_and(|m| unknown(m)) && sets.alone(i)).collect(); - if let Some((&first, rest)) = alone.split_first() { - for &i in rest { - sets.union(i, first); + let mut first = None; + for i in 0..same.len() { + if same.get(i).is_some_and(|m| unknown(m)) && sets.alone(i) { + match first { + None => first = Some(i), + Some(first) => sets.union(i, first), + } } } - let mut groups: HashMap> = HashMap::new(); - for (i, m) in same.iter().enumerate() { - let root = sets.find(i); - groups.entry(root).or_default().push(m.id); - } + // Each message by its set; within one, in order of id, as `same` is. + by_set.clear(); + by_set.extend(same.iter().enumerate().map(|(i, m)| (sets.find(i), m.id))); + by_set.sort_by_key(|(set, _)| *set); self.work = self.work.saturating_add(sets.work); - for mut ids in groups.into_values().filter(|ids| ids.len() > 1) { - ids.sort_unstable(); + let mut rest = by_set.as_slice(); + while let Some(&(set, _)) = rest.first() { + let end = rest.iter().position(|(other, _)| *other != set).unwrap_or(rest.len()); + let (group, after) = rest.split_at(end); + if group.len() > 1 { + let mut ids: Vec = group.iter().map(|(_, id)| *id).collect(); + ids.sort_unstable(); + self.groups.push(ids); + } + rest = after; + } + } + + /// How many messages its conversations hold. + pub fn len(&self) -> usize { + self.groups.iter().map(Vec::len).sum() + } + + /// Whether it holds no conversation of more than one message. + pub fn is_empty(&self) -> bool { + self.groups.is_empty() + } +} + +impl ThreadIndex { + /// The conversations of `messages`: those of one account and one topic, linked as the + /// module's documentation says. + pub fn build<'a>(messages: impl IntoIterator) -> ThreadIndex { + let mut index = ThreadIndex::default(); + let mut topics: HashMap<(Id, String), Vec<&Message>> = HashMap::new(); + for m in messages { + index.work = index.work.saturating_add(1); + let topic = m.topic_key(); + if !topic.is_empty() { + topics.entry((m.account, topic)).or_default().push(m); + } + } + for same in topics.into_values().filter(|same| same.len() > 1) { + index.join(&same); + } + index + } + + /// Work the conversations of some of the topics out again (#1897): `was`, every id those + /// topics had when they were last worked out, and `topics`, the messages of each now, in + /// order of id. What it gives is what [`ThreadIndex::build`] would give of the mailbox as it + /// is now, as long as every topic that changed is among them: a conversation is of one + /// account and one topic, so the others stand as they are. (All of `was` goes first: a + /// message whose subject changed was of one of them and is of another.) + pub fn rejoin(&mut self, was: &[Id], topics: &[Vec<&Message>]) { + for id in was { + self.work = self.work.saturating_add(1); + let key = self.shards.get_mut(shard_of(*id)).and_then(|shard| shard.keys.remove(id)); + if let Some(key) = key + && let Some(shard) = self.shards.get_mut(shard_of(key.0)) + { + shard.members.remove(&key.0); + } + } + for same in topics.iter().filter(|same| same.len() > 1) { + self.join(same); + } + } + + /// Link the messages `same`, all of one account and one topic, into their conversations. + fn join(&mut self, same: &[&Message]) { + self.take_in(Joined::of(same)); + } + + /// Take in the conversations of a topic worked out apart ([`Joined::of`]), as + /// [`ThreadIndex::rejoin`] would work them out: after every id the topic had before is + /// forgotten. + pub fn take_in(&mut self, joined: Joined) { + self.work = self.work.saturating_add(joined.work); + if self.shards.is_empty() { + self.shards = vec![Shard::default(); SHARDS]; + } + for ids in joined.groups { let Some(key) = ids.first().copied().map(ThreadKey) else { continue }; for id in &ids { - self.keys.insert(*id, key); + if let Some(shard) = self.shards.get_mut(shard_of(*id)) { + shard.keys.insert(*id, key); + } } - self.members.insert(key, ids); + if let Some(shard) = self.shards.get_mut(shard_of(key.0)) { + shard.members.insert(key.0, ids); + } + } + } + + /// The index of the conversations `joined`, of topics each worked out apart + /// ([`Joined::of`]), each topic's once: what [`ThreadIndex::build`] gives of their messages. + /// Its parts are filled on up to `threads` threads (a thread that can't be started has its + /// parts filled on this one). + pub fn of_joined(joined: Vec, threads: usize) -> ThreadIndex { + let threads = threads.clamp(1, SHARDS); + let work = joined.iter().fold(0u64, |work, j| work.saturating_add(j.work)); + // The conversations, by the part their key falls in. + let mut groups: Vec>> = vec![Vec::new(); SHARDS]; + for ids in joined.into_iter().flat_map(|j| j.groups) { + if let Some(part) = ids.first().and_then(|key| groups.get_mut(shard_of(*key))) { + part.push(ids); + } + } + // The keys of each part are read from all of them, so each part's own conversations go + // to it after. + let keys = |from: usize| -> Vec<(usize, ById)> { + (from..SHARDS).step_by(threads).map(|at| (at, Shard::of(at, &groups, Vec::new()).keys)).collect() + }; + let mut shards: Vec = vec![Shard::default(); SHARDS]; + let filled: Vec<(usize, ById)> = std::thread::scope(|scope| { + let keys = &keys; + let started: Vec<_> = (1..threads) + .map(|from| (from, std::thread::Builder::new().name("conversations".into()).spawn_scoped(scope, move || keys(from)).ok())) + .collect(); + let mut filled = keys(0); + for (from, thread) in started { + filled.extend(thread.and_then(|t| t.join().ok()).unwrap_or_else(|| keys(from))); + } + filled + }); + for (at, keys) in filled { + if let Some(shard) = shards.get_mut(at) { + shard.keys = keys; + } + } + for (shard, own) in shards.iter_mut().zip(groups) { + shard.members = Shard::of(0, &[], own).members; } + ThreadIndex { shards, work } } /// The conversation of the message `id`: its own when it is linked to no other (or isn't /// among the messages this was built of). pub fn key(&self, id: Id) -> ThreadKey { - self.keys.get(&id).copied().unwrap_or(ThreadKey(id)) + self.shards.get(shard_of(id)).and_then(|shard| shard.keys.get(&id)).copied().unwrap_or(ThreadKey(id)) } /// The ids of the messages of the conversation of the message `id`, smallest first: `id` /// alone when it is linked to no other. pub fn members(&self, id: Id) -> Vec { - self.members.get(&self.key(id)).cloned().unwrap_or_else(|| vec![id]) + let key = self.key(id); + self.shards.get(shard_of(key.0)).and_then(|shard| shard.members.get(&key.0)).cloned().unwrap_or_else(|| vec![id]) } /// Whether the messages `a` and `b` are of one conversation. diff --git a/docs/gaps.md b/docs/gaps.md index 7db172a43..8bfa8289b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -23,7 +23,7 @@ this code base. | 5 | **Microsoft Graph is used for a little; JMAP in the browser build only; no CalDAV or CardDAV, and Exchange servers for mail only.** For accounts that sign in with Microsoft, Graph sends mail, brings the contacts down (read-only) and keeps the account's calendars both ways: appointments, repeating series, meetings (invitations, updates and cancellations sent by the server after the owner's yes), answers to invitations and categories. What is still missing is in [calendar-parity.md](calendar-parity.md): Find a Time over several days, shared calendars, and none of it has met the real service beyond one mailbox. Other providers have no server calendar or contacts, but a calendar on the web can be subscribed to (an `.ics` address, https or webcal, read-only under Other Calendars and refreshed every hour: Internet Calendars, #209); shared mailboxes are read through Graph for any work or school Microsoft account (#70: read through Graph, searched, counted on their own and put among the Favorites; what is changed in them goes up to their own address, deleted mail to their own Deleted Items, and undo with it; mail moves and copies between a shared mailbox and its owner's mailbox or another of his shared mailboxes, made in the destination at its own address and the original removed only once the copy is there; mail written in them is from their address, kept in their own Drafts and sent through them, once the owner has allowed sending from shared mailboxes; each with signatures of its own; their calendars are read once ticked, with the owner's permission asked for by itself and free/busy-only ones drawn as blocks, but not changed from here yet), and the browser build connects only to JMAP servers: the mailboxes, the newest messages and their marks come down, the marks, moves between the server's folders and deletions made here go up, and mail is sent through the server (#1074: an alias with an identity of its own on the server isn't sent from, and who got a blind copy isn't kept after sending), and its contacts are kept in step both ways where the server offers them (#1068, #1076: every address book, shared ones with the rights they give, only the fields changed sent; groups and photos not read); what is changed in folders doesn't go up yet (it can't open the sockets IMAP and SMTP need; [jmap.md](jmap.md)); an Exchange server account (an organisation's own Exchange Server, Grommunio or SmarterMail, reached through Exchange Web Services, #252) (what has been seen on Grommunio, and what has not: [exchange-servers.md](exchange-servers.md)) is a kind of account anyone can add, for its mail only (its calendar and contacts are not kept in step yet), and reads its mail down, and takes up what is changed in it, drafts and sent mail (Send/Receive brings its folders and messages as headers and a preview, then whole messages within Mail to keep offline, from the sync states the server gave; Basic over TLS or NTLMv2 on one held connection, one certificate trusted by its fingerprint; added from Add Account's explicit Exchange server choice: the address and a password, and Server settings for the server's address and the user name; nothing is sent until Connect; the server is found by Autodiscover or taken as typed, the owner is asked (naming the host whole) before the sign-in goes to a host outside their mail domain, and inside it to any host but its Autodiscover host and the hosts its SRV record names (the domain's own name is often a web site, AU3-V1), a mailbox in Microsoft 365 is offered as a Microsoft account with no password sent, the account is tried with one request for its Inbox before it is added, a certificate the system doesn't trust is shown and trusted for that account by its fingerprint only on the owner's tick (asked again from File › Info when it changes, never for an expired or wrong-name one), the password is remembered with the system's credential store when the owner lets it be, and File › Info shows the server, the user name, how it signed in and the trusted certificate, with Forget): Kerberos and modern sign-in are not built, Autodiscover can't sign in with NTLM (a server that wants it is set up by typing its address), a message moved on the server comes as a new one, and one over about 12 MB is not downloaded whole. The DAV foundation has collection/resource snapshots, preserving iCalendar/vCard document edits and a bounded XML reader (`mailcraft-dav`, #376); it does not discover servers, upload changes or sync calendars and contacts. | B | `crates/net/src/graph.rs`, `crates/engine/src/cmd/remote.rs`, `crates/dav` | Anyone who runs meetings from here; everyone not on Microsoft; everyone on the web build | 50–100 | [ROADMAP.md](../ROADMAP.md#after-beta) | | 6 | **HTML mail is close, not exact.** Tables, colours, alignment, sizes, lists, quotes and pictures are shown, adjusted for the dark theme, with nothing run; pictures on the web come only when the owner asks for them, and are kept on this computer for 30 days (`apps/mailcraft/src/picture_cache.rs`); pictures written into the message (`data:`) are shown as attached ones are (#533), and a reply or forward carries them in the original, each as a part of its own as Outlook sends them (#602); a message's `