Skip to main content

vector_core/community/v2/
changes.rs

1//! Typed changes to a Community: what a refresh folded, told apart by comparing what this device
2//! held before it with what it holds after. Local reads only. A session's first look at a
3//! Community is its baseline, so nothing that stood before it reads as new, and a change is
4//! reported only when it is [news](crate::news::is_news): made since the listener began.
5
6use std::cell::OnceCell;
7use std::collections::{BTreeMap, BTreeSet, HashMap};
8use std::sync::Mutex;
9
10use nostr_sdk::prelude::{PublicKey, ToBech32};
11use serde::Serialize;
12
13use super::community::CommunityV2;
14use super::derive;
15use crate::community::roles::{OverwriteTarget, Permissions, Role};
16use crate::community::{ChannelId, CommunityId};
17use crate::event_handler::InboundEventHandler;
18
19/// One change to a Community, who made it and when.
20///
21/// When several people changed the same thing between two looks, the change reads as it stands
22/// now: `by` made its last edit and `also_by` names the others.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
24#[non_exhaustive]
25pub struct CommunityChange {
26    /// The npub that made it: the author of the edition or Guestbook entry that holds it, when
27    /// this device knows it. A lapsed Timeout has none.
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub by: Option<String>,
30    /// When it was made (unix ms), as its author dated it; when this device saw it, if unknown.
31    pub at: u64,
32    /// Everyone else whose edit this change folds in, oldest first.
33    #[serde(skip_serializing_if = "Vec::is_empty")]
34    pub also_by: Vec<String>,
35    #[serde(flatten)]
36    pub kind: ChangeKind,
37}
38
39impl CommunityChange {
40    pub(crate) fn new(by: Option<String>, at: u64, kind: ChangeKind) -> Self {
41        CommunityChange { by, at, also_by: Vec::new(), kind }
42    }
43}
44
45/// A Channel as a change reports it.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
47#[non_exhaustive]
48pub struct ChannelInfo {
49    pub channel_id: String,
50    pub name: String,
51    pub private: bool,
52    pub category_id: Option<String>,
53    pub topic: Option<String>,
54    /// `chat`, `forum` or `voice`.
55    pub view: String,
56}
57
58/// A Category as a change reports it.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
60#[non_exhaustive]
61pub struct CategoryInfo {
62    pub category_id: String,
63    pub name: String,
64}
65
66/// What changed. Members are npubs, every other id is lowercase hex.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
68#[serde(tag = "change", rename_all = "snake_case")]
69#[non_exhaustive]
70pub enum ChangeKind {
71    Renamed { old: String, new: String },
72    DescriptionChanged { old: Option<String>, new: Option<String> },
73    /// The icon's new image URL, `None` when removed.
74    IconChanged { url: Option<String> },
75    BannerChanged { url: Option<String> },
76    RelaysChanged { relays: Vec<String> },
77    VoiceRelaysChanged { relays: Vec<String> },
78    /// What every member holds before any Role; `None` before Roles v2.
79    EveryoneChanged { old: Option<Permissions>, new: Option<Permissions> },
80    RoleCreated { role: Role },
81    /// Its name, colour, permissions or display changed. A move in the order is [`RolesReordered`](Self::RolesReordered).
82    RoleUpdated { old: Role, new: Role },
83    RoleDeleted { role: Role },
84    /// The Role order changed; `order` is every Role id, top first.
85    RolesReordered { order: Vec<String> },
86    MemberRolesChanged { member: String, added: Vec<String>, removed: Vec<String> },
87    MemberBanned { member: String },
88    MemberUnbanned { member: String },
89    MemberKicked { member: String },
90    ChannelCreated { channel: ChannelInfo },
91    ChannelUpdated { old: ChannelInfo, new: ChannelInfo },
92    ChannelDeleted { channel: ChannelInfo },
93    CategoryCreated { category: CategoryInfo },
94    CategoryUpdated { old: CategoryInfo, new: CategoryInfo },
95    CategoryDeleted { category: CategoryInfo },
96    /// The sidebar order of Channels and Categories changed.
97    LayoutChanged,
98    /// A Channel's or Category's overwrite for one target. Both empty: it was removed.
99    OverwriteChanged { scope_id: String, target: OverwriteTarget, allow: Permissions, deny: Permissions },
100    /// A Channel now takes its Category's overwrites (`Some`), or its own again (`None`).
101    ChannelSynced { channel_id: String, category_id: Option<String> },
102    PinsChanged { channel_id: String },
103    /// `until` is unix seconds.
104    TimedOut { member: String, until: u64 },
105    /// Lifted early (with `by`), or lapsed (without). A lapse is seen at the next refresh.
106    TimeoutEnded { member: String },
107    /// `None` when cleared.
108    NicknameChanged { member: String, nickname: Option<String> },
109}
110
111/// What one look at a Community saw.
112#[derive(Default, Clone, PartialEq)]
113struct Snapshot {
114    name: String,
115    description: Option<String>,
116    icon: Option<String>,
117    banner: Option<String>,
118    relays: Vec<String>,
119    voice_relays: Vec<String>,
120    everyone: Option<Permissions>,
121    roles: BTreeMap<String, Role>,
122    role_order: Vec<String>,
123    grants: BTreeMap<String, BTreeSet<String>>,
124    banned: BTreeSet<String>,
125    channels: BTreeMap<String, ChannelInfo>,
126    categories: BTreeMap<String, CategoryInfo>,
127    layout: Vec<String>,
128    overwrites: BTreeMap<(String, OverwriteTarget), (Permissions, Permissions)>,
129    syncs: BTreeMap<String, String>,
130    pins: BTreeMap<String, i64>,
131    timeouts: BTreeMap<String, u64>,
132    nicknames: BTreeMap<String, String>,
133    /// Each Control entity's head version, which bounds the editions a change folds in.
134    heads: BTreeMap<String, u64>,
135}
136
137fn hex(b: &[u8; 32]) -> String {
138    crate::simd::hex::bytes_to_hex_32(b)
139}
140
141fn npub_of_hex(h: &str) -> String {
142    PublicKey::from_hex(h).ok().and_then(|p| p.to_bech32().ok()).unwrap_or_else(|| h.to_string())
143}
144
145fn npub(pk: &PublicKey) -> String {
146    pk.to_bech32().unwrap_or_else(|_| pk.to_hex())
147}
148
149/// Every Channel's settings, in sidebar order.
150pub fn channel_infos(community: &CommunityV2) -> Vec<ChannelInfo> {
151    community
152        .layout()
153        .1
154        .into_iter()
155        .map(|(ch, cat)| ChannelInfo {
156            channel_id: hex(&ch.id.0),
157            name: ch.name.clone(),
158            private: ch.private,
159            category_id: cat.map(|k| hex(&k.id)),
160            topic: ch.topic().map(str::to_string),
161            view: ch.view().as_str().to_string(),
162        })
163        .collect()
164}
165
166/// Every Category, in sidebar order.
167pub fn category_infos(community: &CommunityV2) -> Vec<CategoryInfo> {
168    community.layout().0.into_iter().map(|k| CategoryInfo { category_id: hex(&k.id), name: k.name.clone() }).collect()
169}
170
171/// A Role as it compares: a Roles v2 position is derived from its rank, so only a reorder moves it.
172fn comparable(role: &Role) -> Role {
173    let mut r = role.clone();
174    if r.rank.is_some() {
175        r.position = 0;
176        r.rank = None;
177    }
178    r
179}
180
181/// Whether the items `a` and `b` both hold sit in a different order.
182fn reordered(a: &[String], b: &[String]) -> bool {
183    let both: BTreeSet<&String> = a.iter().filter(|x| b.contains(x)).collect();
184    a.iter().filter(|x| both.contains(x)).ne(b.iter().filter(|x| both.contains(x)))
185}
186
187fn read(community: &CommunityV2) -> Snapshot {
188    let cid = hex(&community.id().0);
189    let roster = crate::db::community::get_community_roles_shared(&cid).unwrap_or_default();
190    let categories = category_infos(community);
191    let mut layout: Vec<String> = categories.iter().map(|k| format!("k{}", k.category_id)).collect();
192    let channel_list = channel_infos(community);
193    layout.extend(channel_list.iter().map(|c| c.channel_id.clone()));
194    let channels = channel_list.into_iter().map(|c| (c.channel_id.clone(), c)).collect();
195    let pins = crate::db::community::get_community_pin_versions(&cid).unwrap_or_default().into_iter().collect();
196    let mut order: Vec<&Role> = roster.roles.iter().collect();
197    order.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
198    Snapshot {
199        name: community.name.clone(),
200        description: community.description.clone(),
201        icon: community.icon.as_ref().map(|i| i.url.clone()),
202        banner: community.banner.as_ref().map(|i| i.url.clone()),
203        relays: community.relays.clone(),
204        voice_relays: community.voice_relays(),
205        everyone: roster.everyone,
206        roles: roster.roles.iter().map(|r| (r.role_id.to_ascii_lowercase(), r.clone())).collect(),
207        role_order: order.iter().map(|r| r.role_id.to_ascii_lowercase()).collect(),
208        grants: roster
209            .grants
210            .iter()
211            .map(|g| (g.member.to_ascii_lowercase(), g.role_ids.iter().map(|r| r.to_ascii_lowercase()).collect()))
212            .collect(),
213        banned: crate::db::community::get_community_banlist(&cid).unwrap_or_default().into_iter().collect(),
214        channels,
215        categories: categories.into_iter().map(|k| (k.category_id.clone(), k)).collect(),
216        layout,
217        overwrites: roster.overwrites.iter().map(|o| ((o.scope.to_ascii_lowercase(), o.target.clone()), (o.allow, o.deny))).collect(),
218        syncs: roster.syncs.clone(),
219        pins,
220        timeouts: super::service::community_timeouts(community)
221            .unwrap_or_default()
222            .into_iter()
223            .map(|(pk, (_, until))| (pk.to_hex(), until))
224            .collect(),
225        nicknames: super::service::nicknames_as_set(community)
226            .unwrap_or_default()
227            .into_iter()
228            .filter(|(_, n)| !n.nick.is_empty())
229            .map(|(pk, n)| (pk.to_hex(), n.nick))
230            .collect(),
231        heads: crate::db::community::get_all_edition_heads_full(&cid).unwrap_or_default().into_iter().map(|(entity, h)| (entity, h.1)).collect(),
232    }
233}
234
235/// Every change `new` makes to `old`, unattributed: [`attribute`] names who made each.
236fn diff(old: &Snapshot, new: &Snapshot) -> Vec<(ChangeKind, Source)> {
237    let mut out = Vec::new();
238    let meta = Source::Entity(Locator::Metadata);
239    if old.name != new.name {
240        out.push((ChangeKind::Renamed { old: old.name.clone(), new: new.name.clone() }, meta.clone()));
241    }
242    if old.description != new.description {
243        out.push((ChangeKind::DescriptionChanged { old: old.description.clone(), new: new.description.clone() }, meta.clone()));
244    }
245    if old.icon != new.icon {
246        out.push((ChangeKind::IconChanged { url: new.icon.clone() }, meta.clone()));
247    }
248    if old.banner != new.banner {
249        out.push((ChangeKind::BannerChanged { url: new.banner.clone() }, meta.clone()));
250    }
251    if old.relays != new.relays {
252        out.push((ChangeKind::RelaysChanged { relays: new.relays.clone() }, meta.clone()));
253    }
254    if old.voice_relays != new.voice_relays {
255        out.push((ChangeKind::VoiceRelaysChanged { relays: new.voice_relays.clone() }, meta));
256    }
257    if old.everyone != new.everyone {
258        out.push((ChangeKind::EveryoneChanged { old: old.everyone, new: new.everyone }, Source::Entity(Locator::Everyone)));
259    }
260    for (id, role) in &new.roles {
261        let at = Source::Entity(Locator::Raw(id.clone()));
262        match old.roles.get(id) {
263            None => out.push((ChangeKind::RoleCreated { role: role.clone() }, at)),
264            Some(was) if comparable(was) != comparable(role) => out.push((ChangeKind::RoleUpdated { old: was.clone(), new: role.clone() }, at)),
265            _ => {}
266        }
267    }
268    for (id, role) in &old.roles {
269        if !new.roles.contains_key(id) {
270            out.push((ChangeKind::RoleDeleted { role: role.clone() }, Source::Entity(Locator::Raw(id.clone()))));
271        }
272    }
273    if reordered(&old.role_order, &new.role_order) {
274        out.push((ChangeKind::RolesReordered { order: new.role_order.clone() }, Source::Unknown));
275    }
276    let none = BTreeSet::new();
277    for member in old.grants.keys().chain(new.grants.keys()).collect::<BTreeSet<_>>() {
278        let (was, now) = (old.grants.get(member).unwrap_or(&none), new.grants.get(member).unwrap_or(&none));
279        if was != now {
280            out.push((
281                ChangeKind::MemberRolesChanged {
282                    member: npub_of_hex(member),
283                    added: now.difference(was).cloned().collect(),
284                    removed: was.difference(now).cloned().collect(),
285                },
286                Source::Entity(Locator::Grant(member.clone())),
287            ));
288        }
289    }
290    for m in new.banned.difference(&old.banned) {
291        out.push((ChangeKind::MemberBanned { member: npub_of_hex(m) }, Source::Entity(Locator::Banlist)));
292    }
293    for m in old.banned.difference(&new.banned) {
294        out.push((ChangeKind::MemberUnbanned { member: npub_of_hex(m) }, Source::Entity(Locator::Banlist)));
295    }
296    for (id, ch) in &new.channels {
297        let at = Source::Entity(Locator::Raw(id.clone()));
298        match old.channels.get(id) {
299            None => out.push((ChangeKind::ChannelCreated { channel: ch.clone() }, at)),
300            Some(was) if was != ch => out.push((ChangeKind::ChannelUpdated { old: was.clone(), new: ch.clone() }, at)),
301            _ => {}
302        }
303    }
304    // A deleted Channel is reported by its purge (`note_channel_deleted`), which also sees one
305    // folded while the session wasn't looking.
306    for (id, k) in &new.categories {
307        let at = Source::Entity(Locator::Raw(id.clone()));
308        match old.categories.get(id) {
309            None => out.push((ChangeKind::CategoryCreated { category: k.clone() }, at)),
310            Some(was) if was != k => out.push((ChangeKind::CategoryUpdated { old: was.clone(), new: k.clone() }, at)),
311            _ => {}
312        }
313    }
314    for (id, k) in &old.categories {
315        if !new.categories.contains_key(id) {
316            out.push((ChangeKind::CategoryDeleted { category: k.clone() }, Source::Entity(Locator::Raw(id.clone()))));
317        }
318    }
319    if reordered(&old.layout, &new.layout) {
320        out.push((ChangeKind::LayoutChanged, Source::Unknown));
321    }
322    let cleared = (Permissions(0), Permissions(0));
323    for key in old.overwrites.keys().chain(new.overwrites.keys()).collect::<BTreeSet<_>>() {
324        let (was, now) = (old.overwrites.get(key).unwrap_or(&cleared), new.overwrites.get(key).unwrap_or(&cleared));
325        if was != now {
326            let (scope_id, target) = key.clone();
327            let at = Source::Entity(Locator::Acl(scope_id.clone(), target.clone()));
328            let target = match target {
329                OverwriteTarget::Member(h) => OverwriteTarget::Member(npub_of_hex(&h)),
330                t => t,
331            };
332            out.push((ChangeKind::OverwriteChanged { scope_id, target, allow: now.0, deny: now.1 }, at));
333        }
334    }
335    for channel in old.syncs.keys().chain(new.syncs.keys()).collect::<BTreeSet<_>>() {
336        let now = new.syncs.get(channel);
337        if old.syncs.get(channel) != now {
338            out.push((
339                ChangeKind::ChannelSynced { channel_id: channel.clone(), category_id: now.cloned() },
340                Source::Entity(Locator::Sync(channel.clone())),
341            ));
342        }
343    }
344    for (channel, version) in &new.pins {
345        if old.pins.get(channel).is_some_and(|v| v != version) || (!old.pins.contains_key(channel) && old.channels.contains_key(channel)) {
346            out.push((ChangeKind::PinsChanged { channel_id: channel.clone() }, Source::Entity(Locator::Pins(channel.clone()))));
347        }
348    }
349    for (member, until) in &new.timeouts {
350        if old.timeouts.get(member) != Some(until) {
351            out.push((ChangeKind::TimedOut { member: npub_of_hex(member), until: *until }, Source::Timeout(member.clone(), *until)));
352        }
353    }
354    for (member, until) in &old.timeouts {
355        if !new.timeouts.contains_key(member) {
356            out.push((ChangeKind::TimeoutEnded { member: npub_of_hex(member) }, Source::TimeoutEnded(member.clone(), *until)));
357        }
358    }
359    for member in old.nicknames.keys().chain(new.nicknames.keys()).collect::<BTreeSet<_>>() {
360        let now = new.nicknames.get(member);
361        if old.nicknames.get(member) != now {
362            out.push((
363                ChangeKind::NicknameChanged { member: npub_of_hex(member), nickname: now.cloned() },
364                Source::Nickname(member.clone()),
365            ));
366        }
367    }
368    out
369}
370
371/// Where a change's author is recorded.
372#[derive(Clone)]
373enum Source {
374    Entity(Locator),
375    /// The newest Timeout entry for this member (hex), setting it to `until`.
376    Timeout(String, u64),
377    /// A member's Timeout to `until` ended: lifted by whoever wrote an entry ending it, or lapsed.
378    TimeoutEnded(String, u64),
379    Nickname(String),
380    Unknown,
381}
382
383/// A Control entity, by what derives its id.
384#[derive(Clone)]
385enum Locator {
386    Metadata,
387    Everyone,
388    Banlist,
389    /// The entity id is the thing's own id: a Role, Channel or Category.
390    Raw(String),
391    Grant(String),
392    Acl(String, OverwriteTarget),
393    Sync(String),
394    Pins(String),
395}
396
397impl Locator {
398    fn entity(&self, cid: &CommunityId) -> Option<[u8; 32]> {
399        let id32 = |h: &str| crate::simd::hex::hex_to_bytes_32_checked(h);
400        Some(match self {
401            Locator::Metadata => cid.0,
402            Locator::Everyone => derive::everyone_locator(cid),
403            Locator::Banlist => derive::banlist_locator(cid),
404            Locator::Raw(id) => id32(id)?,
405            Locator::Grant(member) => derive::grant_locator(cid, &id32(member)?),
406            Locator::Acl(scope, target) => derive::acl_locator(cid, &id32(scope)?, &super::roles::overwrite_target_bytes(cid, target)?),
407            Locator::Sync(channel) => derive::sync_locator(cid, &ChannelId(id32(channel)?)),
408            Locator::Pins(channel) => derive::pins_locator(cid, &ChannelId(id32(channel)?)),
409        })
410    }
411}
412
413/// One edition a fold advanced an entity through.
414#[derive(Clone)]
415struct Mark {
416    version: u64,
417    author: PublicKey,
418    at_ms: u64,
419}
420
421/// Name each change's author and time from what this device holds: the editions the folds since
422/// the last look advanced its entity through (`marks`), else the head of the Control entity that
423/// carries it, or the Guestbook entry. Each source is read once, and only when asked. `seen_at`
424/// dates what has no time of its own.
425fn attribute(community: &CommunityV2, changes: Vec<(ChangeKind, Source)>, marks: &HashMap<String, Vec<Mark>>, seen_at: u64) -> Vec<CommunityChange> {
426    let cid = community.id();
427    let cid_hex = hex(&cid.0);
428    let heads = OnceCell::new();
429    let guestbook = OnceCell::new();
430    let nicknames = OnceCell::new();
431    let head_author = |entity: &str| -> Option<String> {
432        let heads = heads.get_or_init(|| crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap_or_default());
433        let author = heads.get(entity)?.4?;
434        PublicKey::from_slice(&author).ok().map(|p| npub(&p))
435    };
436    let judges = OnceCell::new();
437    // The newest Timeout or Nickname entry aimed at `member` (hex) that its judge lets stand.
438    let newest = |member: &str, timeout: bool| -> Option<(PublicKey, u64, Option<u64>, String)> {
439        use super::guestbook::GuestbookEntry;
440        let events = guestbook.get_or_init(|| crate::db::community::get_guestbook_standing(&cid_hex).ok());
441        let (may_time_out, may_name) = judges.get_or_init(|| (super::service::timeout_judge(community).ok(), super::service::nickname_judge(community).ok()));
442        let target = PublicKey::from_hex(member).ok()?;
443        events
444            .as_ref()?
445            .iter()
446            .filter_map(|e| match &e.entry {
447                GuestbookEntry::Timeout { actor, target: t, at_ms, until_secs, citation } if timeout && *t == target => {
448                    may_time_out.as_ref().is_some_and(|j| j(actor, t, citation.as_ref())).then_some((*actor, *at_ms, Some(*until_secs), String::new()))
449                }
450                GuestbookEntry::Nickname { actor, target: t, at_ms, nick, citation } if !timeout && *t == target => {
451                    may_name.as_ref().is_some_and(|j| j(actor, t, citation.as_ref())).then(|| (*actor, *at_ms, None, nick.clone()))
452                }
453                _ => None,
454            })
455            .max_by_key(|(_, at, _, _)| *at)
456    };
457    // Something moved without one entity to name (a reorder) happened by the newest fold.
458    let newest_fold = marks.values().flatten().map(|m| m.at_ms).max().unwrap_or(seen_at);
459    changes
460        .into_iter()
461        .map(|(kind, source)| {
462            let (by, at, also_by) = match source {
463                Source::Entity(l) => {
464                    let entity = l.entity(cid).map(|e| hex(&e));
465                    match entity.as_ref().and_then(|e| marks.get(e)).and_then(|m| m.last().map(|last| (m, last))) {
466                        Some((all, last)) => {
467                            let mut others: Vec<String> = Vec::new();
468                            for m in &all[..all.len() - 1] {
469                                let who = npub(&m.author);
470                                if m.author != last.author && !others.contains(&who) {
471                                    others.push(who);
472                                }
473                            }
474                            (Some(npub(&last.author)), last.at_ms, others)
475                        }
476                        None => (entity.as_deref().and_then(head_author), seen_at, Vec::new()),
477                    }
478                }
479                Source::Timeout(member, until) => match newest(&member, true).filter(|(_, _, u, _)| *u == Some(until)) {
480                    Some((actor, at_ms, ..)) => (Some(npub(&actor)), at_ms, Vec::new()),
481                    None => (None, seen_at, Vec::new()),
482                },
483                // Lifted by whoever wrote an entry that ends it at once; a lapse has no author.
484                Source::TimeoutEnded(member, until) => {
485                    match newest(&member, true).filter(|(_, at_ms, u, _)| u.is_some_and(|u| u <= at_ms / 1000)) {
486                        Some((actor, at_ms, ..)) => (Some(npub(&actor)), at_ms, Vec::new()),
487                        None => (None, until.saturating_mul(1000).min(seen_at), Vec::new()),
488                    }
489                }
490                Source::Nickname(member) => {
491                    let standing = nicknames.get_or_init(|| super::service::nicknames_as_set(community).unwrap_or_default());
492                    let at = newest(&member, false).map_or(seen_at, |(_, at_ms, ..)| at_ms);
493                    let by = match PublicKey::from_hex(&member).ok().and_then(|pk| standing.get(&pk)).filter(|n| !n.nick.is_empty()) {
494                        Some(n) => Some(npub(&n.actor)),
495                        None => newest(&member, false).filter(|(.., nick)| nick.is_empty()).map(|(a, ..)| npub(&a)),
496                    };
497                    (by, at, Vec::new())
498                }
499                Source::Unknown => (None, newest_fold, Vec::new()),
500            };
501            CommunityChange { by, at, also_by, kind }
502        })
503        .collect()
504}
505
506#[derive(Default)]
507struct Seen(Mutex<HashMap<[u8; 32], Snapshot>>);
508
509/// Changes reported by the work that made them rather than by a comparison, waiting for a
510/// handler: `(community id, change)`.
511#[derive(Default)]
512struct Pending(Mutex<std::collections::VecDeque<(String, CommunityChange)>>);
513
514/// What waits for a handler that never comes (the app's) stays bounded.
515const MAX_PENDING: usize = 256;
516
517fn pending() -> std::sync::Arc<Pending> {
518    crate::db::current_session().scoped::<Pending, _>()
519}
520
521/// A Channel this device just purged as deleted. `community` is the document from before.
522pub(crate) fn note_channel_deleted(community: &CommunityV2, channel: &ChannelId, deleted_by: Option<&PublicKey>) {
523    let ch_hex = hex(&channel.0);
524    let Some(info) = channel_infos(community).into_iter().find(|c| c.channel_id == ch_hex) else { return };
525    let cid_hex = hex(&community.id().0);
526    // The deleting edition, if a fold this session just went through it.
527    let folded_by = folded().0.lock().unwrap_or_else(|e| e.into_inner()).get(&community.id().0).and_then(|e| e.get(&ch_hex)?.last().cloned());
528    let (by, at) = match (deleted_by, folded_by) {
529        (Some(pk), _) => (Some(npub(pk)), crate::clock::now_ms()),
530        (None, Some(mark)) => (Some(npub(&mark.author)), mark.at_ms),
531        (None, None) => (
532            crate::db::community::get_all_edition_heads_full(&cid_hex)
533                .ok()
534                .and_then(|heads| heads.get(&ch_hex)?.4)
535                .and_then(|author| PublicKey::from_slice(&author).ok())
536                .map(|pk| npub(&pk)),
537            crate::clock::now_ms(),
538        ),
539    };
540    // Two purges racing for one Channel report it once.
541    let reported = crate::db::current_session().scoped::<Pending, Mutex<std::collections::HashSet<(String, String)>>>();
542    if !reported.lock().unwrap_or_else(|e| e.into_inner()).insert((cid_hex.clone(), ch_hex)) {
543        return;
544    }
545    let pending = pending();
546    let mut queue = pending.0.lock().unwrap_or_else(|e| e.into_inner());
547    if queue.len() >= MAX_PENDING {
548        queue.pop_front();
549    }
550    queue.push_back((cid_hex, CommunityChange::new(by, at, ChangeKind::ChannelDeleted { channel: info })));
551}
552
553/// Communities a fold is writing now: a look then would see half of it.
554#[derive(Default)]
555struct Persisting(Mutex<std::collections::HashSet<[u8; 32]>>);
556
557fn persisting() -> std::sync::Arc<Persisting> {
558    crate::db::current_session().scoped::<Persisting, _>()
559}
560
561/// Held while a fold writes `community`: a look waits for the fold's own, after it.
562pub(crate) struct PersistGuard(Option<[u8; 32]>);
563
564pub(crate) fn persist_guard(community: &CommunityId) -> PersistGuard {
565    if !wanted() {
566        return PersistGuard(None);
567    }
568    persisting().0.lock().unwrap_or_else(|e| e.into_inner()).insert(community.0);
569    PersistGuard(Some(community.0))
570}
571
572impl Drop for PersistGuard {
573    fn drop(&mut self) {
574        if let Some(id) = self.0 {
575            persisting().0.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
576        }
577    }
578}
579
580/// Each entity's marks, by entity id.
581type Marks = HashMap<String, Vec<Mark>>;
582
583/// The editions folds advanced each entity through since the last look, per Community.
584#[derive(Default)]
585struct Folded(Mutex<HashMap<[u8; 32], Marks>>);
586
587/// What one entity remembers between looks: a fold rarely carries more.
588const MAX_MARKS: usize = 64;
589
590fn folded() -> std::sync::Arc<Folded> {
591    crate::db::current_session().scoped::<Folded, _>()
592}
593
594/// Whether a handler in this session wants the feed: a fold records its editions only then.
595pub(crate) fn wanted() -> bool {
596    crate::db::current_session().scoped::<Wanted, Wanted>().0.load(std::sync::atomic::Ordering::Relaxed)
597}
598
599/// The editions a fold just advanced `entity_hex` through: `(version, author, unix secs)`. A
600/// version a fork settled differently since replaces what was noted for it.
601pub(crate) fn note_folded(community: &CommunityId, entity_hex: &str, chain: Vec<(u64, PublicKey, u64)>) {
602    if chain.is_empty() {
603        return;
604    }
605    let log = folded();
606    let mut held = log.0.lock().unwrap_or_else(|e| e.into_inner());
607    let marks = held.entry(community.0).or_default().entry(entity_hex.to_string()).or_default();
608    for (version, author, secs) in chain {
609        marks.retain(|m| m.version != version);
610        marks.push(Mark { version, author, at_ms: secs.saturating_mul(1000) });
611    }
612    marks.sort_by_key(|m| m.version);
613    let over = marks.len().saturating_sub(MAX_MARKS);
614    marks.drain(..over);
615}
616
617/// What the log holds for `entity_hex`: `(version, author)`, oldest first.
618#[cfg(test)]
619pub(crate) fn folded_marks(community: &CommunityId, entity_hex: &str) -> Vec<(u64, PublicKey)> {
620    folded().0.lock().unwrap().get(&community.0).and_then(|e| e.get(entity_hex)).map(|m| m.iter().map(|m| (m.version, m.author)).collect()).unwrap_or_default()
621}
622
623/// The marks each entity moved through between `was` and `now`, taken. Ones past `now` wait for
624/// the look that reads them, and ones at or below `was` are spent.
625fn take_marks(community: &[u8; 32], was: &Snapshot, now: &Snapshot) -> HashMap<String, Vec<Mark>> {
626    let log = folded();
627    let mut held = log.0.lock().unwrap_or_else(|e| e.into_inner());
628    let Some(entities) = held.get_mut(community) else { return HashMap::new() };
629    let mut out = HashMap::new();
630    entities.retain(|entity, marks| {
631        let floor = was.heads.get(entity).copied().unwrap_or(0);
632        let head = now.heads.get(entity).copied().unwrap_or(0);
633        let (used, later): (Vec<Mark>, Vec<Mark>) = marks.drain(..).filter(|m| m.version > floor).partition(|m| m.version <= head);
634        if !used.is_empty() {
635            out.insert(entity.clone(), used);
636        }
637        *marks = later;
638        !marks.is_empty()
639    });
640    out
641}
642
643/// Hand what waits to `handler`: for one Community, or (`None`) all of them.
644fn deliver_pending(handler: &dyn InboundEventHandler, community_id: Option<&str>) {
645    if !handler.wants_community_changes() {
646        return;
647    }
648    let taken: Vec<(String, CommunityChange)> = {
649        let pending = pending();
650        let mut queue = pending.0.lock().unwrap_or_else(|e| e.into_inner());
651        match community_id {
652            None => queue.drain(..).collect(),
653            Some(cid) => {
654                let (mine, rest): (Vec<_>, Vec<_>) = queue.drain(..).partition(|(c, _)| c == cid);
655                queue.extend(rest);
656                mine
657            }
658        }
659    };
660    for (cid, change) in taken.iter().filter(|(_, c)| !made_here(c) && crate::news::is_news(c.at)) {
661        handler.on_community_change(cid, change);
662    }
663}
664
665fn seen() -> std::sync::Arc<Seen> {
666    crate::db::current_session().scoped::<Seen, _>()
667}
668
669/// Whether a handler in this session asked for the feed: without one, nothing is read for it.
670#[derive(Default)]
671struct Wanted(std::sync::atomic::AtomicBool);
672
673/// Take `community`'s baseline, if the feed is wanted and has none: a Community joined while
674/// listening reports from its join on.
675pub(crate) fn prime(community: &CommunityV2) {
676    if !crate::db::current_session().scoped::<Wanted, Wanted>().0.load(std::sync::atomic::Ordering::Relaxed) {
677        return;
678    }
679    let seen = seen();
680    let mut held = seen.0.lock().unwrap_or_else(|e| e.into_inner());
681    held.entry(community.id().0).or_insert_with(|| read(community));
682}
683
684/// Take the baseline for every Community held, so the first refresh of each reports its
685/// changes rather than becoming the baseline itself, then hand `handler` the deletions the
686/// catch-up purged.
687pub fn prime_all(handler: &dyn InboundEventHandler) {
688    crate::db::current_session().scoped::<Wanted, Wanted>().0.store(true, std::sync::atomic::Ordering::Relaxed);
689    {
690        let seen = seen();
691        let mut held = seen.0.lock().unwrap_or_else(|e| e.into_inner());
692        for id in crate::db::community::list_community_ids().unwrap_or_default() {
693            if let Ok(Some(c)) = crate::db::community::load_community_v2(&id) {
694                held.entry(id.0).or_insert_with(|| read(&c));
695            }
696        }
697    }
698    deliver_pending(handler, None);
699}
700
701/// Drop what was seen of a Community this account no longer holds, so a rejoin starts fresh.
702pub fn forget(community_id: &str) {
703    if let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(community_id) {
704        seen().0.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
705        folded().0.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
706    }
707}
708
709/// Report what changed in `community_id` since the last look, to a handler that asked for it.
710pub fn notify(handler: &dyn InboundEventHandler, community_id: &str) {
711    if !handler.wants_community_changes() {
712        return;
713    }
714    let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(community_id) else { return };
715    if persisting().0.lock().unwrap_or_else(|e| e.into_inner()).contains(&id) {
716        return;
717    }
718    // Everything is read under the lock: two refreshes reading out of order would report a
719    // change and then its undo.
720    let seen = seen();
721    let mut held = seen.0.lock().unwrap_or_else(|e| e.into_inner());
722    let Ok(Some(community)) = crate::db::community::load_community_v2(&CommunityId(id)) else { return };
723    let seen_at = crate::clock::now_ms();
724    let now = read(&community);
725    let changes = match held.insert(id, now.clone()) {
726        Some(was) => {
727            let marks = take_marks(&id, &was, &now);
728            if was == now { Vec::new() } else { attribute(&community, diff(&was, &now), &marks, seen_at) }
729        }
730        // A first look is the baseline: what folded to it is spent.
731        None => {
732            folded().0.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
733            Vec::new()
734        }
735    };
736    drop(held);
737    for change in changes.iter().filter(|c| !made_here(c) && crate::news::is_news(c.at)) {
738        handler.on_community_change(community_id, change);
739    }
740    deliver_pending(handler, Some(community_id));
741}
742
743/// Communities with a look queued by [`notify_soon`].
744#[derive(Default)]
745struct Due(Mutex<std::collections::HashSet<[u8; 32]>>);
746
747/// [`notify`], half a second from now and once for a burst: what any member can cause cheaply,
748/// a Nickname say, never holds up the live feed.
749pub fn notify_soon(handler: std::sync::Arc<dyn InboundEventHandler>, community_id: &str) {
750    if !handler.wants_community_changes() {
751        return;
752    }
753    let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(community_id) else { return };
754    let due = crate::db::current_session().scoped::<Due, Due>();
755    if !due.0.lock().unwrap_or_else(|e| e.into_inner()).insert(id) {
756        return;
757    }
758    let community_id = community_id.to_string();
759    crate::db::spawn_bound(async move {
760        crate::rt::time::sleep(std::time::Duration::from_millis(500)).await;
761        due.0.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
762        notify(&*handler, &community_id);
763    });
764}
765
766/// This account made it: the call that did returned its result, and the comparison would only
767/// report it at whatever refresh came next.
768fn made_here(change: &CommunityChange) -> bool {
769    use nostr_sdk::prelude::ToBech32;
770    let me = crate::state::my_public_key().and_then(|pk| pk.to_bech32().ok());
771    change.by.is_some() && change.by == me
772}
773
774/// Report one change this device saw happen rather than fold, such as an authorized kick.
775pub fn notify_one(handler: &dyn InboundEventHandler, community_id: &str, change: CommunityChange) {
776    if handler.wants_community_changes() && crate::news::is_news(change.at) {
777        handler.on_community_change(community_id, &change);
778    }
779}
780
781#[cfg(test)]
782mod tests {
783    use super::*;
784    use crate::community::transport::memory::MemoryRelay;
785    use nostr_sdk::prelude::Keys;
786
787    fn init() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
788        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
789        crate::db::close_database();
790        crate::db::clear_id_caches();
791        let tmp = tempfile::tempdir().unwrap();
792        static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(93_000);
793        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
794        const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
795        let mut acct = String::from("npub1");
796        let mut v = n as usize;
797        for _ in 0..58 {
798            acct.push(B[v % 32] as char);
799            v = v / 32 + 7;
800        }
801        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
802        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
803        crate::db::set_current_account(acct.clone()).unwrap();
804        crate::db::init_database(&acct).unwrap();
805        let _ = crate::state::take_nostr_client();
806        let me = Keys::generate();
807        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
808        crate::state::set_my_public_key(me.public_key());
809        (tmp, guard, me)
810    }
811
812    #[derive(Default)]
813    struct Changes(Mutex<Vec<CommunityChange>>);
814    impl InboundEventHandler for Changes {
815        fn wants_community_changes(&self) -> bool {
816            true
817        }
818        fn on_community_change(&self, _community_id: &str, change: &CommunityChange) {
819            self.0.lock().unwrap().push(change.clone());
820        }
821    }
822
823    #[tokio::test]
824    async fn a_fold_reports_each_change_once_with_its_author() {
825        let (_tmp, _guard, me) = init();
826        let relay = MemoryRelay::new();
827        let community = super::super::service::create_community(&relay, "Den", vec!["wss://r".into()], None).await.unwrap();
828        let cid = hex(&community.id().0);
829        prime_all(&Changes::default());
830        let meta = super::super::control::CommunityMetadata { name: "Lair".into(), relays: vec!["wss://r".into()], ..Default::default() };
831        super::super::service::edit_community_metadata(&relay, &community, &meta).await.unwrap();
832        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
833        super::super::service::create_category(&relay, &held, "Staff").await.unwrap();
834        let _ = super::super::service::follow_control(&relay, &held).await;
835
836        // Its own changes aren't news to the account that made them.
837        let own = Changes::default();
838        notify(&own, &cid);
839        assert!(own.0.lock().unwrap().is_empty(), "{:?}", own.0.lock().unwrap());
840        // Read as another member would: the same changes, credited to their author.
841        forget(&cid);
842        prime_all(&Changes::default());
843        let category = super::super::service::create_category(&relay, &crate::db::community::load_community_v2(community.id()).unwrap().unwrap(), "Staff 2").await;
844        assert!(category.is_ok());
845        crate::state::set_my_public_key(Keys::generate().public_key());
846
847        let seen = Changes::default();
848        notify(&seen, &cid);
849        let got = seen.0.lock().unwrap().clone();
850        let owner = Some(me.public_key().to_bech32().unwrap());
851        assert!(
852            matches!(&got[..], [CommunityChange { by, kind: ChangeKind::CategoryCreated { category }, .. }] if category.name == "Staff 2" && *by == owner),
853            "one new category, credited to its author: {got:?}"
854        );
855
856        let again = Changes::default();
857        notify(&again, &cid);
858        assert!(again.0.lock().unwrap().is_empty(), "a change is reported once");
859    }
860
861    #[tokio::test]
862    async fn a_deleted_channel_is_reported_by_its_purge_even_unwatched() {
863        let (_tmp, _guard, me) = init();
864        let relay = MemoryRelay::new();
865        let community = super::super::service::create_community(&relay, "Den", vec!["wss://r".into()], None).await.unwrap();
866        let ch = super::super::service::create_public_channel(&relay, &community, "temp").await.unwrap();
867        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
868        crate::VectorCore.register_v2_chats(&held, &crate::db::current_session()).await;
869        // Deleted before any baseline: a catch-up fold, as far as the feed can tell.
870        super::super::service::delete_channel(&relay, &held, &ch, "temp").await.unwrap();
871        crate::state::set_my_public_key(Keys::generate().public_key());
872
873        let seen = Changes::default();
874        prime_all(&seen);
875        let got = seen.0.lock().unwrap().clone();
876        let owner = Some(me.public_key().to_bech32().unwrap());
877        assert!(
878            matches!(&got[..], [CommunityChange { by, kind: ChangeKind::ChannelDeleted { channel }, .. }] if channel.name == "temp" && *by == owner),
879            "{got:?}"
880        );
881        let again = Changes::default();
882        prime_all(&again);
883        assert!(again.0.lock().unwrap().is_empty(), "once");
884    }
885
886    #[tokio::test]
887    async fn a_change_several_people_made_names_each_and_when() {
888        let (_tmp, _guard, me) = init();
889        let relay = MemoryRelay::new();
890        let community = super::super::service::create_community(&relay, "Den", vec!["wss://r".into()], None).await.unwrap();
891        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
892        let mark = |version, author, at_ms| Mark { version, author, at_ms };
893        let marks: HashMap<String, Vec<Mark>> = [(hex(&community.id().0), vec![mark(2, a, 1_000), mark(3, b, 2_000), mark(4, a, 3_000)])].into();
894        let renamed = || vec![(ChangeKind::Renamed { old: "Den".into(), new: "Lair".into() }, Source::Entity(Locator::Metadata))];
895
896        let got = attribute(&community, renamed(), &marks, 9_000);
897        assert_eq!((got[0].by.clone(), got[0].at, got[0].also_by.clone()), (Some(npub(&a)), 3_000, vec![npub(&b)]), "the last edit's author and time, and the other editor");
898
899        let got = attribute(&community, renamed(), &HashMap::new(), 9_000);
900        assert_eq!((got[0].by.clone(), got[0].at), (Some(npub(&me.public_key())), 9_000), "with no fold to read: the head's author, dated when seen");
901    }
902
903    #[tokio::test]
904    async fn a_look_while_a_fold_writes_waits_for_the_folds_own() {
905        let (_tmp, _guard, _me) = init();
906        let relay = MemoryRelay::new();
907        let community = super::super::service::create_community(&relay, "Den", vec!["wss://r".into()], None).await.unwrap();
908        let cid = hex(&community.id().0);
909        prime_all(&Changes::default());
910        super::super::service::create_category(&relay, &community, "Mid-write").await.unwrap();
911        crate::state::set_my_public_key(Keys::generate().public_key());
912
913        let writing = persist_guard(community.id());
914        let early = Changes::default();
915        notify(&early, &cid);
916        assert!(early.0.lock().unwrap().is_empty(), "half a fold is not looked at");
917        drop(writing);
918        let after = Changes::default();
919        notify(&after, &cid);
920        assert!(matches!(&after.0.lock().unwrap()[..], [CommunityChange { kind: ChangeKind::CategoryCreated { .. }, .. }]), "the baseline held: the fold's own look reports it");
921    }
922
923    #[test]
924    fn a_look_takes_the_editions_since_the_last_and_later_ones_wait() {
925        let (_tmp, _guard, _me) = init();
926        let (cid, entity, pk) = (CommunityId([7; 32]), "ee".repeat(32), Keys::generate().public_key());
927        let heads = |v: u64| Snapshot { heads: [(entity.clone(), v)].into(), ..Default::default() };
928        let versions = |taken: &HashMap<String, Vec<Mark>>| taken.get(&entity).map(|m| m.iter().map(|m| m.version).collect::<Vec<_>>()).unwrap_or_default();
929        note_folded(&cid, &entity, vec![(1, pk, 1), (2, pk, 2), (3, pk, 3)]);
930
931        assert_eq!(versions(&take_marks(&cid.0, &heads(1), &heads(2))), vec![2], "the one between the looks; the first was already seen");
932        assert_eq!(versions(&take_marks(&cid.0, &heads(2), &heads(3))), vec![3], "the next waited for its look");
933        assert!(take_marks(&cid.0, &heads(3), &heads(3)).is_empty());
934    }
935
936    fn role(id: &str, name: &str, position: u32, perms: u64) -> Role {
937        Role {
938            role_id: id.into(),
939            name: name.into(),
940            position,
941            permissions: Permissions(perms),
942            scope: crate::community::roles::RoleScope::Server,
943            color: 0,
944            rank: None,
945            display: false,
946            mentionable: false,
947            extra: Default::default(),
948        }
949    }
950
951    fn kinds(old: &Snapshot, new: &Snapshot) -> Vec<ChangeKind> {
952        diff(old, new).into_iter().map(|(k, _)| k).collect()
953    }
954
955    #[test]
956    fn an_unchanged_snapshot_reports_nothing() {
957        let s = Snapshot { name: "Den".into(), ..Default::default() };
958        assert!(kinds(&s, &s.clone()).is_empty());
959    }
960
961    #[test]
962    fn roles_report_create_update_and_delete() {
963        let a = "aa".repeat(32);
964        let b = "bb".repeat(32);
965        let old = Snapshot { roles: [(a.clone(), role(&a, "Mods", 1, 8))].into(), ..Default::default() };
966        let new = Snapshot { roles: [(a.clone(), role(&a, "Moderators", 1, 8)), (b.clone(), role(&b, "VIP", 2, 0))].into(), ..Default::default() };
967        let got = kinds(&old, &new);
968        assert!(got.iter().any(|k| matches!(k, ChangeKind::RoleUpdated { new, .. } if new.name == "Moderators")));
969        assert!(got.iter().any(|k| matches!(k, ChangeKind::RoleCreated { role } if role.name == "VIP")));
970        assert!(kinds(&new, &old).iter().any(|k| matches!(k, ChangeKind::RoleDeleted { role } if role.name == "VIP")));
971    }
972
973    #[test]
974    fn a_reorder_is_one_change_not_one_per_role() {
975        let (a, b) = ("aa".repeat(32), "bb".repeat(32));
976        let ranked = |id: &str, pos: u32, rank: &str| Role { rank: Some(rank.into()), ..role(id, id, pos, 0) };
977        let old = Snapshot { roles: [(a.clone(), ranked(&a, 1, "m")), (b.clone(), ranked(&b, 2, "t"))].into(), role_order: vec![a.clone(), b.clone()], ..Default::default() };
978        let new = Snapshot { roles: [(a.clone(), ranked(&a, 2, "x")), (b.clone(), ranked(&b, 1, "t"))].into(), role_order: vec![b.clone(), a.clone()], ..Default::default() };
979        assert_eq!(kinds(&old, &new), vec![ChangeKind::RolesReordered { order: vec![b, a] }]);
980    }
981
982    #[test]
983    fn a_new_channel_moves_nothing_and_a_swap_does() {
984        let (x, y, z) = ("x".repeat(64), "y".repeat(64), "z".repeat(64));
985        let at = |ids: &[&String]| Snapshot { layout: ids.iter().map(|s| s.to_string()).collect(), ..Default::default() };
986        assert!(!kinds(&at(&[&x, &y]), &at(&[&x, &z, &y])).contains(&ChangeKind::LayoutChanged), "an insertion keeps the others' order");
987        assert!(kinds(&at(&[&x, &y]), &at(&[&y, &x])).contains(&ChangeKind::LayoutChanged));
988    }
989
990    #[test]
991    fn a_grant_reports_only_the_roles_it_moved() {
992        let m = "cc".repeat(32);
993        let old = Snapshot { grants: [(m.clone(), ["r1".to_string(), "r2".to_string()].into())].into(), ..Default::default() };
994        let new = Snapshot { grants: [(m.clone(), ["r2".to_string(), "r3".to_string()].into())].into(), ..Default::default() };
995        let got = kinds(&old, &new);
996        assert_eq!(got.len(), 1);
997        let ChangeKind::MemberRolesChanged { added, removed, .. } = &got[0] else { panic!("{got:?}") };
998        assert_eq!((added.as_slice(), removed.as_slice()), (&["r3".to_string()][..], &["r1".to_string()][..]));
999    }
1000
1001    #[test]
1002    fn bans_timeouts_and_nicknames_read_both_ways() {
1003        let m = "dd".repeat(32);
1004        let old = Snapshot { nicknames: [(m.clone(), "kit".to_string())].into(), ..Default::default() };
1005        let new = Snapshot { banned: [m.clone()].into(), timeouts: [(m.clone(), 99)].into(), ..Default::default() };
1006        let got = kinds(&old, &new);
1007        assert!(got.iter().any(|k| matches!(k, ChangeKind::MemberBanned { .. })));
1008        assert!(got.iter().any(|k| matches!(k, ChangeKind::TimedOut { until: 99, .. })));
1009        assert!(got.iter().any(|k| matches!(k, ChangeKind::NicknameChanged { nickname: None, .. })));
1010        let back = kinds(&new, &old);
1011        assert!(back.iter().any(|k| matches!(k, ChangeKind::MemberUnbanned { .. })));
1012        assert!(back.iter().any(|k| matches!(k, ChangeKind::TimeoutEnded { .. })));
1013    }
1014
1015    #[test]
1016    fn a_removed_overwrite_reports_empty_bits() {
1017        let key = ("ee".repeat(32), OverwriteTarget::Everyone);
1018        let old = Snapshot { overwrites: [(key, (Permissions(1 << 14), Permissions(0)))].into(), ..Default::default() };
1019        let got = kinds(&old, &Snapshot::default());
1020        assert!(matches!(&got[..], [ChangeKind::OverwriteChanged { allow: Permissions(0), deny: Permissions(0), .. }]));
1021    }
1022
1023    #[test]
1024    fn a_new_channel_with_pins_reports_the_channel_not_the_pins() {
1025        let ch = "ff".repeat(32);
1026        let info = ChannelInfo { channel_id: ch.clone(), name: "general".into(), private: false, category_id: None, topic: None, view: "chat".into() };
1027        let new = Snapshot { channels: [(ch.clone(), info)].into(), pins: [(ch.clone(), 1)].into(), layout: vec![ch.clone()], ..Default::default() };
1028        let got = kinds(&Snapshot::default(), &new);
1029        assert!(got.iter().any(|k| matches!(k, ChangeKind::ChannelCreated { .. })));
1030        assert!(!got.iter().any(|k| matches!(k, ChangeKind::PinsChanged { .. })));
1031    }
1032}