atagen

macltok

public
Star0
Watch0
66db1b3cd8955da257726f2f3028b931ba34c3c0
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git

Blame: src/engine/watchers.rs

411bc1c78b65atagen2026-10-22 07:39 UTC1
use std::{
e5c6427adb35atagen2026-10-25 10:23 UTC2
    collections::{BTreeMap, HashMap, HashSet, VecDeque},
411bc1c78b65atagen2026-10-22 07:39 UTC3
    sync::Arc,
411bc1c78b65atagen2026-10-22 07:39 UTC4
    time::Duration,
411bc1c78b65atagen2026-10-22 07:39 UTC5
};
31ce2453c82fatagen2026-09-24 13:07 UTC6
31ce2453c82fatagen2026-09-24 13:07 UTC7
use futures_util::StreamExt;
31ce2453c82fatagen2026-09-24 13:07 UTC8
use matrix_sdk::{
e5c6427adb35atagen2026-10-25 10:23 UTC9
    Client, Room,
31ce2453c82fatagen2026-09-24 13:07 UTC10
    ruma::events::{AnyMessageLikeEventContent, room::message::MessageType},
0bfa3f46f0beatagen2026-09-26 09:12 UTC11
    send_queue::{LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate},
31ce2453c82fatagen2026-09-24 13:07 UTC12
};
17e042fbc331atagen2026-10-08 12:39 UTC13
use matrix_sdk_base::RoomInfoNotableUpdateReasons;
31ce2453c82fatagen2026-09-24 13:07 UTC14
use matrix_sdk_ui::sync_service::{State as SyncState, SyncService};
17e042fbc331atagen2026-10-08 12:39 UTC15
use ruma::{
e5c6427adb35atagen2026-10-25 10:23 UTC16
    OwnedEventId, OwnedRoomId, OwnedTransactionId,
e5c6427adb35atagen2026-10-25 10:23 UTC17
    events::{
e5c6427adb35atagen2026-10-25 10:23 UTC18
        AnyGlobalAccountDataEvent, AnyRoomAccountDataEvent, AnySyncStateEvent,
e5c6427adb35atagen2026-10-25 10:23 UTC19
        receipt::SyncReceiptEvent,
e5c6427adb35atagen2026-10-25 10:23 UTC20
    },
17e042fbc331atagen2026-10-08 12:39 UTC21
    serde::Raw,
17e042fbc331atagen2026-10-08 12:39 UTC22
    time::Instant,
17e042fbc331atagen2026-10-08 12:39 UTC23
};
e5c6427adb35atagen2026-10-25 10:23 UTC24
use tokio::sync::{Notify, broadcast::error::RecvError, mpsc, watch};
31ce2453c82fatagen2026-09-24 13:07 UTC25
f12377bce9b9atagen2026-09-26 12:32 UTC26
use super::executor::TaskSet;
31ce2453c82fatagen2026-09-24 13:07 UTC27
use crate::{
e5c6427adb35atagen2026-10-25 10:23 UTC28
    ConnectionState, Event, ThreadUnread, UploadOutcome,
17e042fbc331atagen2026-10-08 12:39 UTC29
    encryption::encryption_state,
17e042fbc331atagen2026-10-08 12:39 UTC30
    error::classify_sdk_error,
e5c6427adb35atagen2026-10-25 10:23 UTC31
    normalise::{ENABLED_ROOMS, ROOM_PACKS, USER_PACK, thread_unreads},
9bd34e25bb86atagen2026-10-24 07:23 UTC32
    space_order,
f12377bce9b9atagen2026-09-26 12:32 UTC33
    transport::EventSender,
31ce2453c82fatagen2026-09-24 13:07 UTC34
};
31ce2453c82fatagen2026-09-24 13:07 UTC35
31ce2453c82fatagen2026-09-24 13:07 UTC36
const SYNC_RESTART_MIN: Duration = Duration::from_secs(1);
31ce2453c82fatagen2026-09-24 13:07 UTC37
const SYNC_RESTART_MAX: Duration = Duration::from_secs(60);
31ce2453c82fatagen2026-09-24 13:07 UTC38
const SEND_QUEUE_RETRY: Duration = Duration::from_secs(5);
5a52012c9b1datagen2026-09-24 23:45 UTC39
const SYNC_STABLE: Duration = Duration::from_secs(30);
5a52012c9b1datagen2026-09-24 23:45 UTC40
5a52012c9b1datagen2026-09-24 23:45 UTC41
pub(super) async fn room_subscriptions(
5a52012c9b1datagen2026-09-24 23:45 UTC42
    sync: Arc<SyncService>,
5a52012c9b1datagen2026-09-24 23:45 UTC43
    mut rooms: watch::Receiver<Vec<ruma::OwnedRoomId>>,
5a52012c9b1datagen2026-09-24 23:45 UTC44
) {
5a52012c9b1datagen2026-09-24 23:45 UTC45
    while rooms.changed().await.is_ok() {
5a52012c9b1datagen2026-09-24 23:45 UTC46
        let room_ids = rooms.borrow_and_update().clone();
5a52012c9b1datagen2026-09-24 23:45 UTC47
        let room_ids = room_ids.iter().map(AsRef::as_ref).collect::<Vec<_>>();
5a52012c9b1datagen2026-09-24 23:45 UTC48
        sync.room_list_service().subscribe_to_rooms(&room_ids).await;
5a52012c9b1datagen2026-09-24 23:45 UTC49
    }
5a52012c9b1datagen2026-09-24 23:45 UTC50
}
31ce2453c82fatagen2026-09-24 13:07 UTC51
31ce2453c82fatagen2026-09-24 13:07 UTC52
/// `states` must be taken before sync starts, a late subscriber never hears the transition it missed
31ce2453c82fatagen2026-09-24 13:07 UTC53
pub(super) async fn connection(
31ce2453c82fatagen2026-09-24 13:07 UTC54
    mut states: impl futures_util::Stream<Item = SyncState> + Unpin,
31ce2453c82fatagen2026-09-24 13:07 UTC55
    sync: Arc<SyncService>,
31ce2453c82fatagen2026-09-24 13:07 UTC56
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC57
    events: EventSender,
31ce2453c82fatagen2026-09-24 13:07 UTC58
    connection: watch::Sender<ConnectionState>,
31ce2453c82fatagen2026-09-24 13:07 UTC59
) {
31ce2453c82fatagen2026-09-24 13:07 UTC60
    let mut backoff = SYNC_RESTART_MIN;
5a52012c9b1datagen2026-09-24 23:45 UTC61
    let mut online_since: Option<Instant> = None;
31ce2453c82fatagen2026-09-24 13:07 UTC62
    while let Some(state) = states.next().await {
5a52012c9b1datagen2026-09-24 23:45 UTC63
        // only a run that lasted counts as recovered, or a server that answers /versions
5a52012c9b1datagen2026-09-24 23:45 UTC64
        // but refuses sync would have us bounce between offline and online forever
5a52012c9b1datagen2026-09-24 23:45 UTC65
        let stable = online_since
5a52012c9b1datagen2026-09-24 23:45 UTC66
            .take()
5a52012c9b1datagen2026-09-24 23:45 UTC67
            .map(|since| since.elapsed() >= SYNC_STABLE);
5a52012c9b1datagen2026-09-24 23:45 UTC68
        if stable == Some(true) {
5a52012c9b1datagen2026-09-24 23:45 UTC69
            backoff = SYNC_RESTART_MIN;
5a52012c9b1datagen2026-09-24 23:45 UTC70
        }
31ce2453c82fatagen2026-09-24 13:07 UTC71
        let (state, restart) = match state {
5a52012c9b1datagen2026-09-24 23:45 UTC72
            // only ever us stopping it for a restart, nothing a client needs to hear
5a52012c9b1datagen2026-09-24 23:45 UTC73
            SyncState::Idle => continue,
31ce2453c82fatagen2026-09-24 13:07 UTC74
            SyncState::Running => {
5a52012c9b1datagen2026-09-24 23:45 UTC75
                online_since = Some(Instant::now());
31ce2453c82fatagen2026-09-24 13:07 UTC76
                // the sdk parks a room queue on any send error and never unparks it
31ce2453c82fatagen2026-09-24 13:07 UTC77
                client.send_queue().set_enabled(true).await;
31ce2453c82fatagen2026-09-24 13:07 UTC78
                (ConnectionState::Online, false)
31ce2453c82fatagen2026-09-24 13:07 UTC79
            }
5a52012c9b1datagen2026-09-24 23:45 UTC80
            SyncState::Offline => (ConnectionState::Offline, stable == Some(false)),
31ce2453c82fatagen2026-09-24 13:07 UTC81
            SyncState::Terminated => (ConnectionState::Offline, true),
31ce2453c82fatagen2026-09-24 13:07 UTC82
            SyncState::Error(error) => {
31ce2453c82fatagen2026-09-24 13:07 UTC83
                tracing::warn!(%error, "sync service reported an error");
31ce2453c82fatagen2026-09-24 13:07 UTC84
                (ConnectionState::Offline, true)
31ce2453c82fatagen2026-09-24 13:07 UTC85
            }
31ce2453c82fatagen2026-09-24 13:07 UTC86
        };
31ce2453c82fatagen2026-09-24 13:07 UTC87
        if *connection.borrow() != state {
31ce2453c82fatagen2026-09-24 13:07 UTC88
            connection.send_replace(state);
31ce2453c82fatagen2026-09-24 13:07 UTC89
            if events.send(Event::ConnectionChanged(state)).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC90
                return;
31ce2453c82fatagen2026-09-24 13:07 UTC91
            }
31ce2453c82fatagen2026-09-24 13:07 UTC92
        }
31ce2453c82fatagen2026-09-24 13:07 UTC93
        if restart {
5a52012c9b1datagen2026-09-24 23:45 UTC94
            sync.stop().await;
1fe480c16a3catagen2026-09-26 08:44 UTC95
            matrix_sdk::sleep::sleep(backoff).await;
31ce2453c82fatagen2026-09-24 13:07 UTC96
            backoff = (backoff * 2).min(SYNC_RESTART_MAX);
31ce2453c82fatagen2026-09-24 13:07 UTC97
            sync.start().await;
31ce2453c82fatagen2026-09-24 13:07 UTC98
        }
31ce2453c82fatagen2026-09-24 13:07 UTC99
    }
31ce2453c82fatagen2026-09-24 13:07 UTC100
}
31ce2453c82fatagen2026-09-24 13:07 UTC101
31ce2453c82fatagen2026-09-24 13:07 UTC102
/// a recoverable failure while we're online is a hiccup, so give the room another go
31ce2453c82fatagen2026-09-24 13:07 UTC103
pub(super) async fn send_queue_errors(
31ce2453c82fatagen2026-09-24 13:07 UTC104
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC105
    mut errors: tokio::sync::broadcast::Receiver<matrix_sdk::send_queue::SendQueueRoomError>,
31ce2453c82fatagen2026-09-24 13:07 UTC106
    online: watch::Receiver<ConnectionState>,
31ce2453c82fatagen2026-09-24 13:07 UTC107
) {
1fe480c16a3catagen2026-09-26 08:44 UTC108
    let mut retries = TaskSet::new();
31ce2453c82fatagen2026-09-24 13:07 UTC109
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC110
        let error = tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC111
            error = errors.recv() => error,
31ce2453c82fatagen2026-09-24 13:07 UTC112
            Some(_) = retries.join_next(), if !retries.is_empty() => continue,
31ce2453c82fatagen2026-09-24 13:07 UTC113
        };
31ce2453c82fatagen2026-09-24 13:07 UTC114
        match error {
31ce2453c82fatagen2026-09-24 13:07 UTC115
            Ok(error) if error.is_recoverable => {
31ce2453c82fatagen2026-09-24 13:07 UTC116
                let client = client.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC117
                let online = online.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC118
                retries.spawn(async move {
1fe480c16a3catagen2026-09-26 08:44 UTC119
                    matrix_sdk::sleep::sleep(SEND_QUEUE_RETRY).await;
31ce2453c82fatagen2026-09-24 13:07 UTC120
                    if *online.borrow() == ConnectionState::Online
31ce2453c82fatagen2026-09-24 13:07 UTC121
                        && let Some(room) = client.get_room(&error.room_id)
31ce2453c82fatagen2026-09-24 13:07 UTC122
                    {
31ce2453c82fatagen2026-09-24 13:07 UTC123
                        room.send_queue().set_enabled(true);
31ce2453c82fatagen2026-09-24 13:07 UTC124
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC125
                });
31ce2453c82fatagen2026-09-24 13:07 UTC126
            }
31ce2453c82fatagen2026-09-24 13:07 UTC127
            Ok(_) | Err(RecvError::Lagged(_)) => {}
31ce2453c82fatagen2026-09-24 13:07 UTC128
            Err(RecvError::Closed) => return,
31ce2453c82fatagen2026-09-24 13:07 UTC129
        }
31ce2453c82fatagen2026-09-24 13:07 UTC130
    }
31ce2453c82fatagen2026-09-24 13:07 UTC131
}
31ce2453c82fatagen2026-09-24 13:07 UTC132
7c26fad34822atagen2026-09-26 09:41 UTC133
/// the one place upload events leave from, so an upload is never reported after it
411bc1c78b65atagen2026-10-22 07:39 UTC134
/// ended. the client-wide channel exists before any upload does. it holds 32 updates and
411bc1c78b65atagen2026-10-22 07:39 UTC135
/// progress ticks share it, so this keeps draining while the event stream is full
0bfa3f46f0beatagen2026-09-26 09:12 UTC136
pub(super) async fn uploads(
5a52012c9b1datagen2026-09-24 23:45 UTC137
    client: Client,
0bfa3f46f0beatagen2026-09-26 09:12 UTC138
    mut updates: tokio::sync::broadcast::Receiver<SendQueueUpdate>,
5a52012c9b1datagen2026-09-24 23:45 UTC139
    events: EventSender,
5a52012c9b1datagen2026-09-24 23:45 UTC140
) {
0bfa3f46f0beatagen2026-09-26 09:12 UTC141
    let (_, mut rooms) = client.rooms_stream();
411bc1c78b65atagen2026-10-22 07:39 UTC142
    let mut tracker = UploadTracker::new(attachment_echoes(&client).await);
411bc1c78b65atagen2026-10-22 07:39 UTC143
    let mut pending = VecDeque::new();
5a52012c9b1datagen2026-09-24 23:45 UTC144
    loop {
411bc1c78b65atagen2026-10-22 07:39 UTC145
        let reports: Vec<Event> = tokio::select! {
411bc1c78b65atagen2026-10-22 07:39 UTC146
            biased;
0bfa3f46f0beatagen2026-09-26 09:12 UTC147
            update = updates.recv() => match update {
7c26fad34822atagen2026-09-26 09:41 UTC148
                Ok(update) => tracker.update(update).into_iter().collect(),
0bfa3f46f0beatagen2026-09-26 09:12 UTC149
                Err(RecvError::Lagged(skipped)) => {
7cf348521204atagen2026-09-26 12:28 UTC150
                    tracing::warn!(skipped, "upload tracker lagged");
7cf348521204atagen2026-09-26 12:28 UTC151
                    tracker.resnapshot(attachment_echoes(&client).await)
0bfa3f46f0beatagen2026-09-26 09:12 UTC152
                }
0bfa3f46f0beatagen2026-09-26 09:12 UTC153
                Err(RecvError::Closed) => return,
0bfa3f46f0beatagen2026-09-26 09:12 UTC154
            },
0bfa3f46f0beatagen2026-09-26 09:12 UTC155
            update = rooms.next() => {
0bfa3f46f0beatagen2026-09-26 09:12 UTC156
                if update.is_none() {
0bfa3f46f0beatagen2026-09-26 09:12 UTC157
                    return;
0bfa3f46f0beatagen2026-09-26 09:12 UTC158
                }
7c26fad34822atagen2026-09-26 09:41 UTC159
                tracker.finish_where(
7c26fad34822atagen2026-09-26 09:41 UTC160
                    |(room_id, _)| client.get_room(room_id).is_none(),
7c26fad34822atagen2026-09-26 09:41 UTC161
                    &UploadOutcome::RoomForgotten,
7c26fad34822atagen2026-09-26 09:41 UTC162
                )
31ce2453c82fatagen2026-09-24 13:07 UTC163
            }
411bc1c78b65atagen2026-10-22 07:39 UTC164
            permit = events.reserve(), if !pending.is_empty() => {
411bc1c78b65atagen2026-10-22 07:39 UTC165
                let Ok(permit) = permit else { return };
411bc1c78b65atagen2026-10-22 07:39 UTC166
                permit.send(pending.pop_front().expect("pending was checked"));
411bc1c78b65atagen2026-10-22 07:39 UTC167
                continue;
411bc1c78b65atagen2026-10-22 07:39 UTC168
            }
31ce2453c82fatagen2026-09-24 13:07 UTC169
        };
7c26fad34822atagen2026-09-26 09:41 UTC170
        for event in reports {
411bc1c78b65atagen2026-10-22 07:39 UTC171
            queue_upload_event(&mut pending, event);
411bc1c78b65atagen2026-10-22 07:39 UTC172
        }
411bc1c78b65atagen2026-10-22 07:39 UTC173
    }
411bc1c78b65atagen2026-10-22 07:39 UTC174
}
411bc1c78b65atagen2026-10-22 07:39 UTC175
411bc1c78b65atagen2026-10-22 07:39 UTC176
/// a progress tick replaces a waiting one for the same upload, unless something else about
411bc1c78b65atagen2026-10-22 07:39 UTC177
/// that upload is queued after it
411bc1c78b65atagen2026-10-22 07:39 UTC178
fn queue_upload_event(pending: &mut VecDeque<Event>, event: Event) {
411bc1c78b65atagen2026-10-22 07:39 UTC179
    if matches!(event, Event::MediaUploadProgress { .. })
411bc1c78b65atagen2026-10-22 07:39 UTC180
        && let Some(waiting) = pending
411bc1c78b65atagen2026-10-22 07:39 UTC181
            .iter_mut()
411bc1c78b65atagen2026-10-22 07:39 UTC182
            .rev()
411bc1c78b65atagen2026-10-22 07:39 UTC183
            .find(|waiting| upload_of(waiting) == upload_of(&event))
411bc1c78b65atagen2026-10-22 07:39 UTC184
        && matches!(waiting, Event::MediaUploadProgress { .. })
411bc1c78b65atagen2026-10-22 07:39 UTC185
    {
411bc1c78b65atagen2026-10-22 07:39 UTC186
        *waiting = event;
411bc1c78b65atagen2026-10-22 07:39 UTC187
        return;
411bc1c78b65atagen2026-10-22 07:39 UTC188
    }
411bc1c78b65atagen2026-10-22 07:39 UTC189
    pending.push_back(event);
411bc1c78b65atagen2026-10-22 07:39 UTC190
}
411bc1c78b65atagen2026-10-22 07:39 UTC191
411bc1c78b65atagen2026-10-22 07:39 UTC192
fn upload_of(event: &Event) -> Option<(&OwnedRoomId, &OwnedTransactionId)> {
411bc1c78b65atagen2026-10-22 07:39 UTC193
    match event {
411bc1c78b65atagen2026-10-22 07:39 UTC194
        Event::MediaUploadProgress {
411bc1c78b65atagen2026-10-22 07:39 UTC195
            room_id,
411bc1c78b65atagen2026-10-22 07:39 UTC196
            transaction_id,
411bc1c78b65atagen2026-10-22 07:39 UTC197
            ..
411bc1c78b65atagen2026-10-22 07:39 UTC198
        }
411bc1c78b65atagen2026-10-22 07:39 UTC199
        | Event::MediaUploadFailed {
411bc1c78b65atagen2026-10-22 07:39 UTC200
            room_id,
411bc1c78b65atagen2026-10-22 07:39 UTC201
            transaction_id,
411bc1c78b65atagen2026-10-22 07:39 UTC202
            ..
0bfa3f46f0beatagen2026-09-26 09:12 UTC203
        }
411bc1c78b65atagen2026-10-22 07:39 UTC204
        | Event::MediaUploadFinished {
411bc1c78b65atagen2026-10-22 07:39 UTC205
            room_id,
411bc1c78b65atagen2026-10-22 07:39 UTC206
            transaction_id,
411bc1c78b65atagen2026-10-22 07:39 UTC207
            ..
411bc1c78b65atagen2026-10-22 07:39 UTC208
        } => Some((room_id, transaction_id)),
411bc1c78b65atagen2026-10-22 07:39 UTC209
        _ => None,
0bfa3f46f0beatagen2026-09-26 09:12 UTC210
    }
0bfa3f46f0beatagen2026-09-26 09:12 UTC211
}
0bfa3f46f0beatagen2026-09-26 09:12 UTC212
0bfa3f46f0beatagen2026-09-26 09:12 UTC213
type Upload = (OwnedRoomId, OwnedTransactionId);
0bfa3f46f0beatagen2026-09-26 09:12 UTC214
411bc1c78b65atagen2026-10-22 07:39 UTC215
/// the sdk sends progress ticks from a detached task, so a tick can land after its
411bc1c78b65atagen2026-10-22 07:39 UTC216
/// upload's end. it trails by one task hop, so a short memory of ends covers it
411bc1c78b65atagen2026-10-22 07:39 UTC217
const REMEMBERED_ENDS: usize = 256;
411bc1c78b65atagen2026-10-22 07:39 UTC218
411bc1c78b65atagen2026-10-22 07:39 UTC219
/// everything reported gets exactly one `MediaUploadFinished` and nothing after it
7c26fad34822atagen2026-09-26 09:41 UTC220
struct UploadTracker {
7c26fad34822atagen2026-09-26 09:41 UTC221
    live: HashSet<Upload>,
7c26fad34822atagen2026-09-26 09:41 UTC222
    ended: HashSet<Upload>,
411bc1c78b65atagen2026-10-22 07:39 UTC223
    ended_order: VecDeque<Upload>,
0bfa3f46f0beatagen2026-09-26 09:12 UTC224
}
0bfa3f46f0beatagen2026-09-26 09:12 UTC225
7c26fad34822atagen2026-09-26 09:41 UTC226
impl UploadTracker {
411bc1c78b65atagen2026-10-22 07:39 UTC227
    fn new(live: HashSet<Upload>) -> Self {
411bc1c78b65atagen2026-10-22 07:39 UTC228
        Self {
411bc1c78b65atagen2026-10-22 07:39 UTC229
            live,
411bc1c78b65atagen2026-10-22 07:39 UTC230
            ended: HashSet::new(),
411bc1c78b65atagen2026-10-22 07:39 UTC231
            ended_order: VecDeque::new(),
411bc1c78b65atagen2026-10-22 07:39 UTC232
        }
411bc1c78b65atagen2026-10-22 07:39 UTC233
    }
411bc1c78b65atagen2026-10-22 07:39 UTC234
7c26fad34822atagen2026-09-26 09:41 UTC235
    fn update(&mut self, update: SendQueueUpdate) -> Option<Event> {
7c26fad34822atagen2026-09-26 09:41 UTC236
        let room_id = update.room_id;
7c26fad34822atagen2026-09-26 09:41 UTC237
        let (transaction_id, outcome) = match update.update {
7c26fad34822atagen2026-09-26 09:41 UTC238
            RoomSendQueueUpdate::NewLocalEvent(echo) => {
7c26fad34822atagen2026-09-26 09:41 UTC239
                let upload = (room_id, echo.transaction_id);
7c26fad34822atagen2026-09-26 09:41 UTC240
                if is_attachment_echo(&echo.content) && !self.ended.contains(&upload) {
7c26fad34822atagen2026-09-26 09:41 UTC241
                    self.live.insert(upload);
7c26fad34822atagen2026-09-26 09:41 UTC242
                }
0bfa3f46f0beatagen2026-09-26 09:12 UTC243
                return None;
0bfa3f46f0beatagen2026-09-26 09:12 UTC244
            }
411bc1c78b65atagen2026-10-22 07:39 UTC245
            RoomSendQueueUpdate::MediaUpload {
411bc1c78b65atagen2026-10-22 07:39 UTC246
                related_to,
411bc1c78b65atagen2026-10-22 07:39 UTC247
                file,
411bc1c78b65atagen2026-10-22 07:39 UTC248
                progress,
411bc1c78b65atagen2026-10-22 07:39 UTC249
                ..
411bc1c78b65atagen2026-10-22 07:39 UTC250
            } => {
411bc1c78b65atagen2026-10-22 07:39 UTC251
                let upload = (room_id, related_to);
411bc1c78b65atagen2026-10-22 07:39 UTC252
                if self.ended.contains(&upload) {
411bc1c78b65atagen2026-10-22 07:39 UTC253
                    return None;
411bc1c78b65atagen2026-10-22 07:39 UTC254
                }
411bc1c78b65atagen2026-10-22 07:39 UTC255
                self.live.insert(upload.clone());
411bc1c78b65atagen2026-10-22 07:39 UTC256
                let (room_id, transaction_id) = upload;
411bc1c78b65atagen2026-10-22 07:39 UTC257
                return Some(Event::MediaUploadProgress {
411bc1c78b65atagen2026-10-22 07:39 UTC258
                    room_id,
411bc1c78b65atagen2026-10-22 07:39 UTC259
                    transaction_id,
411bc1c78b65atagen2026-10-22 07:39 UTC260
                    uploaded_bytes: progress.current as u64,
411bc1c78b65atagen2026-10-22 07:39 UTC261
                    total_bytes: progress.total as u64,
411bc1c78b65atagen2026-10-22 07:39 UTC262
                    complete: file.is_some() && progress.current == progress.total,
411bc1c78b65atagen2026-10-22 07:39 UTC263
                });
411bc1c78b65atagen2026-10-22 07:39 UTC264
            }
7c26fad34822atagen2026-09-26 09:41 UTC265
            RoomSendQueueUpdate::SendError {
0bfa3f46f0beatagen2026-09-26 09:12 UTC266
                transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC267
                error,
7c26fad34822atagen2026-09-26 09:41 UTC268
                is_recoverable,
7c26fad34822atagen2026-09-26 09:41 UTC269
            } => {
7c26fad34822atagen2026-09-26 09:41 UTC270
                let upload = (room_id, transaction_id);
7c26fad34822atagen2026-09-26 09:41 UTC271
                if !self.live.contains(&upload) {
7c26fad34822atagen2026-09-26 09:41 UTC272
                    return None;
7c26fad34822atagen2026-09-26 09:41 UTC273
                }
7c26fad34822atagen2026-09-26 09:41 UTC274
                let (room_id, transaction_id) = upload;
7c26fad34822atagen2026-09-26 09:41 UTC275
                return Some(Event::MediaUploadFailed {
7c26fad34822atagen2026-09-26 09:41 UTC276
                    room_id,
7c26fad34822atagen2026-09-26 09:41 UTC277
                    transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC278
                    kind: classify_sdk_error(&error),
7c26fad34822atagen2026-09-26 09:41 UTC279
                    will_retry: is_recoverable,
7c26fad34822atagen2026-09-26 09:41 UTC280
                });
7c26fad34822atagen2026-09-26 09:41 UTC281
            }
7c26fad34822atagen2026-09-26 09:41 UTC282
            RoomSendQueueUpdate::SentEvent {
7c26fad34822atagen2026-09-26 09:41 UTC283
                transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC284
                event_id,
7c26fad34822atagen2026-09-26 09:41 UTC285
            } => (transaction_id, UploadOutcome::Sent { event_id }),
7c26fad34822atagen2026-09-26 09:41 UTC286
            RoomSendQueueUpdate::CancelledLocalEvent { transaction_id } => {
7c26fad34822atagen2026-09-26 09:41 UTC287
                (transaction_id, UploadOutcome::Cancelled)
7c26fad34822atagen2026-09-26 09:41 UTC288
            }
7c26fad34822atagen2026-09-26 09:41 UTC289
            _ => return None,
7c26fad34822atagen2026-09-26 09:41 UTC290
        };
411bc1c78b65atagen2026-10-22 07:39 UTC291
        self.finish((room_id, transaction_id), outcome)
7c26fad34822atagen2026-09-26 09:41 UTC292
    }
7c26fad34822atagen2026-09-26 09:41 UTC293
7c26fad34822atagen2026-09-26 09:41 UTC294
    fn resnapshot(&mut self, current: HashSet<Upload>) -> Vec<Event> {
7c26fad34822atagen2026-09-26 09:41 UTC295
        let reports = self.finish_where(|upload| !current.contains(upload), &UploadOutcome::Missed);
7c26fad34822atagen2026-09-26 09:41 UTC296
        let ended = &self.ended;
7c26fad34822atagen2026-09-26 09:41 UTC297
        self.live
7c26fad34822atagen2026-09-26 09:41 UTC298
            .extend(current.into_iter().filter(|upload| !ended.contains(upload)));
7c26fad34822atagen2026-09-26 09:41 UTC299
        reports
7c26fad34822atagen2026-09-26 09:41 UTC300
    }
7c26fad34822atagen2026-09-26 09:41 UTC301
7c26fad34822atagen2026-09-26 09:41 UTC302
    fn finish_where(
7c26fad34822atagen2026-09-26 09:41 UTC303
        &mut self,
7c26fad34822atagen2026-09-26 09:41 UTC304
        ends: impl Fn(&Upload) -> bool,
7c26fad34822atagen2026-09-26 09:41 UTC305
        outcome: &UploadOutcome,
7c26fad34822atagen2026-09-26 09:41 UTC306
    ) -> Vec<Event> {
7c26fad34822atagen2026-09-26 09:41 UTC307
        let ending = self
7c26fad34822atagen2026-09-26 09:41 UTC308
            .live
7c26fad34822atagen2026-09-26 09:41 UTC309
            .iter()
7c26fad34822atagen2026-09-26 09:41 UTC310
            .filter(|upload| ends(upload))
7c26fad34822atagen2026-09-26 09:41 UTC311
            .cloned()
7c26fad34822atagen2026-09-26 09:41 UTC312
            .collect::<Vec<_>>();
7c26fad34822atagen2026-09-26 09:41 UTC313
        ending
7c26fad34822atagen2026-09-26 09:41 UTC314
            .into_iter()
411bc1c78b65atagen2026-10-22 07:39 UTC315
            .filter_map(|upload| self.finish(upload, outcome.clone()))
7c26fad34822atagen2026-09-26 09:41 UTC316
            .collect()
7c26fad34822atagen2026-09-26 09:41 UTC317
    }
7c26fad34822atagen2026-09-26 09:41 UTC318
411bc1c78b65atagen2026-10-22 07:39 UTC319
    /// an end for an upload we never saw is remembered too, its ticks may still be coming
411bc1c78b65atagen2026-10-22 07:39 UTC320
    fn finish(&mut self, upload: Upload, outcome: UploadOutcome) -> Option<Event> {
411bc1c78b65atagen2026-10-22 07:39 UTC321
        if self.ended.insert(upload.clone()) {
411bc1c78b65atagen2026-10-22 07:39 UTC322
            self.ended_order.push_back(upload.clone());
411bc1c78b65atagen2026-10-22 07:39 UTC323
            if self.ended_order.len() > REMEMBERED_ENDS
411bc1c78b65atagen2026-10-22 07:39 UTC324
                && let Some(oldest) = self.ended_order.pop_front()
411bc1c78b65atagen2026-10-22 07:39 UTC325
            {
411bc1c78b65atagen2026-10-22 07:39 UTC326
                self.ended.remove(&oldest);
411bc1c78b65atagen2026-10-22 07:39 UTC327
            }
411bc1c78b65atagen2026-10-22 07:39 UTC328
        }
7c26fad34822atagen2026-09-26 09:41 UTC329
        if !self.live.remove(&upload) {
7c26fad34822atagen2026-09-26 09:41 UTC330
            return None;
31ce2453c82fatagen2026-09-24 13:07 UTC331
        }
7c26fad34822atagen2026-09-26 09:41 UTC332
        let (room_id, transaction_id) = upload;
7c26fad34822atagen2026-09-26 09:41 UTC333
        Some(Event::MediaUploadFinished {
7c26fad34822atagen2026-09-26 09:41 UTC334
            room_id,
7c26fad34822atagen2026-09-26 09:41 UTC335
            transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC336
            outcome,
7c26fad34822atagen2026-09-26 09:41 UTC337
        })
31ce2453c82fatagen2026-09-24 13:07 UTC338
    }
0bfa3f46f0beatagen2026-09-26 09:12 UTC339
}
0bfa3f46f0beatagen2026-09-26 09:12 UTC340
7c26fad34822atagen2026-09-26 09:41 UTC341
async fn attachment_echoes(client: &Client) -> HashSet<Upload> {
7c26fad34822atagen2026-09-26 09:41 UTC342
    let Ok(echoes) = client.send_queue().local_echoes().await else {
7c26fad34822atagen2026-09-26 09:41 UTC343
        return HashSet::new();
7c26fad34822atagen2026-09-26 09:41 UTC344
    };
7c26fad34822atagen2026-09-26 09:41 UTC345
    echoes
0bfa3f46f0beatagen2026-09-26 09:12 UTC346
        .into_iter()
7c26fad34822atagen2026-09-26 09:41 UTC347
        .flat_map(|(room_id, echoes)| {
7c26fad34822atagen2026-09-26 09:41 UTC348
            echoes
7c26fad34822atagen2026-09-26 09:41 UTC349
                .into_iter()
7c26fad34822atagen2026-09-26 09:41 UTC350
                .filter(|echo| is_attachment_echo(&echo.content))
7c26fad34822atagen2026-09-26 09:41 UTC351
                .map(move |echo| (room_id.clone(), echo.transaction_id))
0bfa3f46f0beatagen2026-09-26 09:12 UTC352
        })
0bfa3f46f0beatagen2026-09-26 09:12 UTC353
        .collect()
31ce2453c82fatagen2026-09-24 13:07 UTC354
}
31ce2453c82fatagen2026-09-24 13:07 UTC355
31ce2453c82fatagen2026-09-24 13:07 UTC356
fn is_attachment_echo(content: &LocalEchoContent) -> bool {
31ce2453c82fatagen2026-09-24 13:07 UTC357
    let LocalEchoContent::Event {
31ce2453c82fatagen2026-09-24 13:07 UTC358
        serialized_event, ..
31ce2453c82fatagen2026-09-24 13:07 UTC359
    } = content
31ce2453c82fatagen2026-09-24 13:07 UTC360
    else {
31ce2453c82fatagen2026-09-24 13:07 UTC361
        return false;
31ce2453c82fatagen2026-09-24 13:07 UTC362
    };
31ce2453c82fatagen2026-09-24 13:07 UTC363
    matches!(
31ce2453c82fatagen2026-09-24 13:07 UTC364
        serialized_event.deserialize(),
31ce2453c82fatagen2026-09-24 13:07 UTC365
        Ok(AnyMessageLikeEventContent::RoomMessage(content))
31ce2453c82fatagen2026-09-24 13:07 UTC366
            if matches!(
31ce2453c82fatagen2026-09-24 13:07 UTC367
                content.msgtype,
31ce2453c82fatagen2026-09-24 13:07 UTC368
                MessageType::Audio(_) | MessageType::File(_) | MessageType::Image(_) | MessageType::Video(_)
31ce2453c82fatagen2026-09-24 13:07 UTC369
            )
31ce2453c82fatagen2026-09-24 13:07 UTC370
    )
31ce2453c82fatagen2026-09-24 13:07 UTC371
}
31ce2453c82fatagen2026-09-24 13:07 UTC372
31ce2453c82fatagen2026-09-24 13:07 UTC373
pub(super) async fn encryption(client: Client, events: EventSender) {
31ce2453c82fatagen2026-09-24 13:07 UTC374
    let Some(device_id) = client.device_id().map(ToOwned::to_owned) else {
31ce2453c82fatagen2026-09-24 13:07 UTC375
        tracing::warn!("encryption watcher stopped because the client has no device id");
31ce2453c82fatagen2026-09-24 13:07 UTC376
        return;
31ce2453c82fatagen2026-09-24 13:07 UTC377
    };
31ce2453c82fatagen2026-09-24 13:07 UTC378
    let recovery = client.encryption().recovery();
31ce2453c82fatagen2026-09-24 13:07 UTC379
    let backups = client.encryption().backups();
31ce2453c82fatagen2026-09-24 13:07 UTC380
    let mut recovery_stream = recovery.state_stream();
31ce2453c82fatagen2026-09-24 13:07 UTC381
    let mut backup_stream = backups.state_stream();
31ce2453c82fatagen2026-09-24 13:07 UTC382
    let mut verification_stream = client.encryption().verification_state();
31ce2453c82fatagen2026-09-24 13:07 UTC383
    let mut recovery_state = recovery.state();
31ce2453c82fatagen2026-09-24 13:07 UTC384
    let mut backup_state = backups.state();
31ce2453c82fatagen2026-09-24 13:07 UTC385
    let mut verification_state = verification_stream.get();
31ce2453c82fatagen2026-09-24 13:07 UTC386
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC387
        let state = encryption_state(
31ce2453c82fatagen2026-09-24 13:07 UTC388
            device_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC389
            recovery_state,
31ce2453c82fatagen2026-09-24 13:07 UTC390
            verification_state,
31ce2453c82fatagen2026-09-24 13:07 UTC391
            backup_state,
31ce2453c82fatagen2026-09-24 13:07 UTC392
        );
31ce2453c82fatagen2026-09-24 13:07 UTC393
        if events.send(Event::EncryptionChanged(state)).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC394
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC395
        }
31ce2453c82fatagen2026-09-24 13:07 UTC396
        tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC397
            Some(update) = recovery_stream.next() => recovery_state = update,
31ce2453c82fatagen2026-09-24 13:07 UTC398
            Some(update) = verification_stream.next() => verification_state = update,
31ce2453c82fatagen2026-09-24 13:07 UTC399
            Some(update) = backup_stream.next() => {
31ce2453c82fatagen2026-09-24 13:07 UTC400
                backup_state = update.unwrap_or_else(|_| backups.state());
31ce2453c82fatagen2026-09-24 13:07 UTC401
            }
31ce2453c82fatagen2026-09-24 13:07 UTC402
            else => return,
31ce2453c82fatagen2026-09-24 13:07 UTC403
        }
31ce2453c82fatagen2026-09-24 13:07 UTC404
    }
31ce2453c82fatagen2026-09-24 13:07 UTC405
}
31ce2453c82fatagen2026-09-24 13:07 UTC406
fa5b4e09943aatagen2026-10-24 09:33 UTC407
/// space orders, pins and power levels all feed summaries without raising a notable room info update
31ce2453c82fatagen2026-09-24 13:07 UTC408
pub(super) async fn rooms(client: Client, events: EventSender) {
31ce2453c82fatagen2026-09-24 13:07 UTC409
    let (_, mut rooms) = client.rooms_stream();
31ce2453c82fatagen2026-09-24 13:07 UTC410
    let mut info = client.room_info_notable_update_receiver();
fa5b4e09943aatagen2026-10-24 09:33 UTC411
    let changed = Arc::new(Notify::new());
fa5b4e09943aatagen2026-10-24 09:33 UTC412
    let handlers = [
fa5b4e09943aatagen2026-10-24 09:33 UTC413
        client.add_event_handler({
fa5b4e09943aatagen2026-10-24 09:33 UTC414
            let changed = changed.clone();
fa5b4e09943aatagen2026-10-24 09:33 UTC415
            move |event: Raw<AnyRoomAccountDataEvent>| {
fa5b4e09943aatagen2026-10-24 09:33 UTC416
                let changed = changed.clone();
fa5b4e09943aatagen2026-10-24 09:33 UTC417
                async move {
fa5b4e09943aatagen2026-10-24 09:33 UTC418
                    if event_type(&event).as_deref() == Some(space_order::EVENT_TYPE) {
fa5b4e09943aatagen2026-10-24 09:33 UTC419
                        changed.notify_one();
fa5b4e09943aatagen2026-10-24 09:33 UTC420
                    }
9bd34e25bb86atagen2026-10-24 07:23 UTC421
                }
9bd34e25bb86atagen2026-10-24 07:23 UTC422
            }
fa5b4e09943aatagen2026-10-24 09:33 UTC423
        }),
fa5b4e09943aatagen2026-10-24 09:33 UTC424
        client.add_event_handler({
fa5b4e09943aatagen2026-10-24 09:33 UTC425
            let changed = changed.clone();
fa5b4e09943aatagen2026-10-24 09:33 UTC426
            move |event: Raw<AnySyncStateEvent>| {
fa5b4e09943aatagen2026-10-24 09:33 UTC427
                let changed = changed.clone();
fa5b4e09943aatagen2026-10-24 09:33 UTC428
                async move {
fa5b4e09943aatagen2026-10-24 09:33 UTC429
                    if matches!(
fa5b4e09943aatagen2026-10-24 09:33 UTC430
                        event_type(&event).as_deref(),
fa5b4e09943aatagen2026-10-24 09:33 UTC431
                        Some("m.room.pinned_events" | "m.room.power_levels")
fa5b4e09943aatagen2026-10-24 09:33 UTC432
                    ) {
fa5b4e09943aatagen2026-10-24 09:33 UTC433
                        changed.notify_one();
fa5b4e09943aatagen2026-10-24 09:33 UTC434
                    }
fa5b4e09943aatagen2026-10-24 09:33 UTC435
                }
fa5b4e09943aatagen2026-10-24 09:33 UTC436
            }
fa5b4e09943aatagen2026-10-24 09:33 UTC437
        }),
fa5b4e09943aatagen2026-10-24 09:33 UTC438
    ];
e5c6427adb35atagen2026-10-25 10:23 UTC439
    let (receipts, mut receipt_rooms) = mpsc::unbounded_channel();
e5c6427adb35atagen2026-10-25 10:23 UTC440
    let receipt_handler = client.add_event_handler(move |_: SyncReceiptEvent, room: Room| {
e5c6427adb35atagen2026-10-25 10:23 UTC441
        let _ = receipts.send(room.room_id().to_owned());
e5c6427adb35atagen2026-10-25 10:23 UTC442
        async {}
e5c6427adb35atagen2026-10-25 10:23 UTC443
    });
e5c6427adb35atagen2026-10-25 10:23 UTC444
    let mut timelines = client.event_cache().subscribe_to_room_generic_updates();
e5c6427adb35atagen2026-10-25 10:23 UTC445
    let mut thread_unreads = ThreadUnreads::default();
e5c6427adb35atagen2026-10-25 10:23 UTC446
    'invalidate: loop {
31ce2453c82fatagen2026-09-24 13:07 UTC447
        if events.send(Event::RoomsChanged).await.is_err() {
9bd34e25bb86atagen2026-10-24 07:23 UTC448
            break;
31ce2453c82fatagen2026-09-24 13:07 UTC449
        }
e5c6427adb35atagen2026-10-25 10:23 UTC450
        // thread events and threaded receipts leave room info alone, so neither reaches `info`
e5c6427adb35atagen2026-10-25 10:23 UTC451
        loop {
e5c6427adb35atagen2026-10-25 10:23 UTC452
            let room_id = tokio::select! {
e5c6427adb35atagen2026-10-25 10:23 UTC453
                update = rooms.next() => if update.is_none() { break 'invalidate } else { break },
e5c6427adb35atagen2026-10-25 10:23 UTC454
                update = info.recv() => {
e5c6427adb35atagen2026-10-25 10:23 UTC455
                    if matches!(update, Err(RecvError::Closed)) { break 'invalidate }
e5c6427adb35atagen2026-10-25 10:23 UTC456
                    break;
e5c6427adb35atagen2026-10-25 10:23 UTC457
                }
e5c6427adb35atagen2026-10-25 10:23 UTC458
                () = changed.notified() => break,
e5c6427adb35atagen2026-10-25 10:23 UTC459
                Some(room_id) = receipt_rooms.recv() => room_id,
e5c6427adb35atagen2026-10-25 10:23 UTC460
                update = timelines.recv() => match update {
e5c6427adb35atagen2026-10-25 10:23 UTC461
                    Ok(update) => update.room_id,
e5c6427adb35atagen2026-10-25 10:23 UTC462
                    Err(RecvError::Lagged(_)) => {
e5c6427adb35atagen2026-10-25 10:23 UTC463
                        thread_unreads.0.clear();
e5c6427adb35atagen2026-10-25 10:23 UTC464
                        break;
e5c6427adb35atagen2026-10-25 10:23 UTC465
                    }
e5c6427adb35atagen2026-10-25 10:23 UTC466
                    Err(RecvError::Closed) => break 'invalidate,
e5c6427adb35atagen2026-10-25 10:23 UTC467
                },
e5c6427adb35atagen2026-10-25 10:23 UTC468
            };
e5c6427adb35atagen2026-10-25 10:23 UTC469
            if thread_unreads.changed(&client, room_id).await {
e5c6427adb35atagen2026-10-25 10:23 UTC470
                break;
e5c6427adb35atagen2026-10-25 10:23 UTC471
            }
31ce2453c82fatagen2026-09-24 13:07 UTC472
        }
31ce2453c82fatagen2026-09-24 13:07 UTC473
        // a sync touching fifty rooms is one invalidation, not fifty
31ce2453c82fatagen2026-09-24 13:07 UTC474
        while let Ok(_) | Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) =
31ce2453c82fatagen2026-09-24 13:07 UTC475
            info.try_recv()
31ce2453c82fatagen2026-09-24 13:07 UTC476
        {}
31ce2453c82fatagen2026-09-24 13:07 UTC477
    }
e5c6427adb35atagen2026-10-25 10:23 UTC478
    for handler in handlers.into_iter().chain([receipt_handler]) {
fa5b4e09943aatagen2026-10-24 09:33 UTC479
        client.remove_event_handler(handler);
fa5b4e09943aatagen2026-10-24 09:33 UTC480
    }
31ce2453c82fatagen2026-09-24 13:07 UTC481
}
31ce2453c82fatagen2026-09-24 13:07 UTC482
e5c6427adb35atagen2026-10-25 10:23 UTC483
#[derive(Default)]
e5c6427adb35atagen2026-10-25 10:23 UTC484
struct ThreadUnreads(HashMap<OwnedRoomId, BTreeMap<OwnedEventId, ThreadUnread>>);
e5c6427adb35atagen2026-10-25 10:23 UTC485
e5c6427adb35atagen2026-10-25 10:23 UTC486
impl ThreadUnreads {
e5c6427adb35atagen2026-10-25 10:23 UTC487
    async fn changed(&mut self, client: &Client, room_id: OwnedRoomId) -> bool {
e5c6427adb35atagen2026-10-25 10:23 UTC488
        let Some(room) = client.get_room(&room_id) else {
e5c6427adb35atagen2026-10-25 10:23 UTC489
            return self.0.remove(&room_id).is_some();
e5c6427adb35atagen2026-10-25 10:23 UTC490
        };
e5c6427adb35atagen2026-10-25 10:23 UTC491
        let unreads = thread_unreads(&room).await;
e5c6427adb35atagen2026-10-25 10:23 UTC492
        if self
e5c6427adb35atagen2026-10-25 10:23 UTC493
            .0
e5c6427adb35atagen2026-10-25 10:23 UTC494
            .get(&room_id)
e5c6427adb35atagen2026-10-25 10:23 UTC495
            .map_or(unreads.is_empty(), |known| *known == unreads)
e5c6427adb35atagen2026-10-25 10:23 UTC496
        {
e5c6427adb35atagen2026-10-25 10:23 UTC497
            return false;
e5c6427adb35atagen2026-10-25 10:23 UTC498
        }
e5c6427adb35atagen2026-10-25 10:23 UTC499
        self.0.insert(room_id, unreads);
e5c6427adb35atagen2026-10-25 10:23 UTC500
        true
e5c6427adb35atagen2026-10-25 10:23 UTC501
    }
e5c6427adb35atagen2026-10-25 10:23 UTC502
}
e5c6427adb35atagen2026-10-25 10:23 UTC503
17e042fbc331atagen2026-10-08 12:39 UTC504
/// packs live in room state and account data, and leaving a room takes its packs with it
17e042fbc331atagen2026-10-08 12:39 UTC505
pub(super) async fn image_packs(client: Client, events: EventSender) {
17e042fbc331atagen2026-10-08 12:39 UTC506
    let changed = Arc::new(Notify::new());
17e042fbc331atagen2026-10-08 12:39 UTC507
    let handlers = [
17e042fbc331atagen2026-10-08 12:39 UTC508
        client.add_event_handler({
17e042fbc331atagen2026-10-08 12:39 UTC509
            let changed = changed.clone();
17e042fbc331atagen2026-10-08 12:39 UTC510
            move |event: Raw<AnySyncStateEvent>| {
17e042fbc331atagen2026-10-08 12:39 UTC511
                let changed = changed.clone();
17e042fbc331atagen2026-10-08 12:39 UTC512
                async move {
17e042fbc331atagen2026-10-08 12:39 UTC513
                    if event_type(&event).as_deref() == Some(ROOM_PACKS) {
17e042fbc331atagen2026-10-08 12:39 UTC514
                        changed.notify_one();
17e042fbc331atagen2026-10-08 12:39 UTC515
                    }
17e042fbc331atagen2026-10-08 12:39 UTC516
                }
17e042fbc331atagen2026-10-08 12:39 UTC517
            }
17e042fbc331atagen2026-10-08 12:39 UTC518
        }),
17e042fbc331atagen2026-10-08 12:39 UTC519
        client.add_event_handler({
17e042fbc331atagen2026-10-08 12:39 UTC520
            let changed = changed.clone();
17e042fbc331atagen2026-10-08 12:39 UTC521
            move |event: Raw<AnyGlobalAccountDataEvent>| {
17e042fbc331atagen2026-10-08 12:39 UTC522
                let changed = changed.clone();
17e042fbc331atagen2026-10-08 12:39 UTC523
                async move {
17e042fbc331atagen2026-10-08 12:39 UTC524
                    if matches!(
17e042fbc331atagen2026-10-08 12:39 UTC525
                        event_type(&event).as_deref(),
17e042fbc331atagen2026-10-08 12:39 UTC526
                        Some(USER_PACK | ENABLED_ROOMS)
17e042fbc331atagen2026-10-08 12:39 UTC527
                    ) {
17e042fbc331atagen2026-10-08 12:39 UTC528
                        changed.notify_one();
17e042fbc331atagen2026-10-08 12:39 UTC529
                    }
17e042fbc331atagen2026-10-08 12:39 UTC530
                }
17e042fbc331atagen2026-10-08 12:39 UTC531
            }
17e042fbc331atagen2026-10-08 12:39 UTC532
        }),
17e042fbc331atagen2026-10-08 12:39 UTC533
    ];
17e042fbc331atagen2026-10-08 12:39 UTC534
    let mut info = client.room_info_notable_update_receiver();
17e042fbc331atagen2026-10-08 12:39 UTC535
    loop {
17e042fbc331atagen2026-10-08 12:39 UTC536
        tokio::select! {
17e042fbc331atagen2026-10-08 12:39 UTC537
            () = changed.notified() => {}
17e042fbc331atagen2026-10-08 12:39 UTC538
            update = info.recv() => match update {
17e042fbc331atagen2026-10-08 12:39 UTC539
                Ok(update) if !update.reasons.contains(RoomInfoNotableUpdateReasons::MEMBERSHIP) => {
17e042fbc331atagen2026-10-08 12:39 UTC540
                    continue;
17e042fbc331atagen2026-10-08 12:39 UTC541
                }
17e042fbc331atagen2026-10-08 12:39 UTC542
                Ok(_) | Err(RecvError::Lagged(_)) => {}
17e042fbc331atagen2026-10-08 12:39 UTC543
                Err(RecvError::Closed) => break,
17e042fbc331atagen2026-10-08 12:39 UTC544
            },
17e042fbc331atagen2026-10-08 12:39 UTC545
        }
17e042fbc331atagen2026-10-08 12:39 UTC546
        if events.send(Event::ImagePacksChanged).await.is_err() {
17e042fbc331atagen2026-10-08 12:39 UTC547
            break;
17e042fbc331atagen2026-10-08 12:39 UTC548
        }
17e042fbc331atagen2026-10-08 12:39 UTC549
    }
17e042fbc331atagen2026-10-08 12:39 UTC550
    for handler in handlers {
17e042fbc331atagen2026-10-08 12:39 UTC551
        client.remove_event_handler(handler);
17e042fbc331atagen2026-10-08 12:39 UTC552
    }
17e042fbc331atagen2026-10-08 12:39 UTC553
}
17e042fbc331atagen2026-10-08 12:39 UTC554
17e042fbc331atagen2026-10-08 12:39 UTC555
fn event_type<T>(event: &Raw<T>) -> Option<String> {
17e042fbc331atagen2026-10-08 12:39 UTC556
    event.get_field("type").ok().flatten()
17e042fbc331atagen2026-10-08 12:39 UTC557
}
17e042fbc331atagen2026-10-08 12:39 UTC558
31ce2453c82fatagen2026-09-24 13:07 UTC559
pub(super) async fn notification_settings(client: Client, events: EventSender) {
31ce2453c82fatagen2026-09-24 13:07 UTC560
    let settings = client.notification_settings().await;
31ce2453c82fatagen2026-09-24 13:07 UTC561
    let mut changes = settings.subscribe_to_changes();
31ce2453c82fatagen2026-09-24 13:07 UTC562
    while let Ok(()) | Err(RecvError::Lagged(_)) = changes.recv().await {
0bfa3f46f0beatagen2026-09-26 09:12 UTC563
        // room summaries carry the effective mode, and push rule changes never touch room info
0bfa3f46f0beatagen2026-09-26 09:12 UTC564
        for event in [Event::NotificationSettingsChanged, Event::RoomsChanged] {
0bfa3f46f0beatagen2026-09-26 09:12 UTC565
            if events.send(event).await.is_err() {
0bfa3f46f0beatagen2026-09-26 09:12 UTC566
                return;
0bfa3f46f0beatagen2026-09-26 09:12 UTC567
            }
31ce2453c82fatagen2026-09-24 13:07 UTC568
        }
31ce2453c82fatagen2026-09-24 13:07 UTC569
    }
31ce2453c82fatagen2026-09-24 13:07 UTC570
}
7c26fad34822atagen2026-09-26 09:41 UTC571
7c26fad34822atagen2026-09-26 09:41 UTC572
#[cfg(test)]
7c26fad34822atagen2026-09-26 09:41 UTC573
mod tests {
411bc1c78b65atagen2026-10-22 07:39 UTC574
    use matrix_sdk::send_queue::{AbstractProgress, RoomSendQueueUpdate, SendQueueUpdate};
7c26fad34822atagen2026-09-26 09:41 UTC575
    use ruma::{OwnedTransactionId, event_id, owned_room_id};
7c26fad34822atagen2026-09-26 09:41 UTC576
411bc1c78b65atagen2026-10-22 07:39 UTC577
    use super::{HashSet, Upload, UploadTracker};
7c26fad34822atagen2026-09-26 09:41 UTC578
    use crate::{Event, UploadOutcome};
7c26fad34822atagen2026-09-26 09:41 UTC579
7cf348521204atagen2026-09-26 12:28 UTC580
    fn upload() -> Upload {
7cf348521204atagen2026-09-26 12:28 UTC581
        (
7c26fad34822atagen2026-09-26 09:41 UTC582
            owned_room_id!("!room:localhost"),
7c26fad34822atagen2026-09-26 09:41 UTC583
            OwnedTransactionId::from("upload"),
7cf348521204atagen2026-09-26 12:28 UTC584
        )
7cf348521204atagen2026-09-26 12:28 UTC585
    }
7cf348521204atagen2026-09-26 12:28 UTC586
411bc1c78b65atagen2026-10-22 07:39 UTC587
    fn update(update: RoomSendQueueUpdate) -> SendQueueUpdate {
411bc1c78b65atagen2026-10-22 07:39 UTC588
        SendQueueUpdate {
411bc1c78b65atagen2026-10-22 07:39 UTC589
            room_id: upload().0,
411bc1c78b65atagen2026-10-22 07:39 UTC590
            update,
7cf348521204atagen2026-09-26 12:28 UTC591
        }
7cf348521204atagen2026-09-26 12:28 UTC592
    }
7cf348521204atagen2026-09-26 12:28 UTC593
411bc1c78b65atagen2026-10-22 07:39 UTC594
    fn tick() -> SendQueueUpdate {
411bc1c78b65atagen2026-10-22 07:39 UTC595
        update(RoomSendQueueUpdate::MediaUpload {
411bc1c78b65atagen2026-10-22 07:39 UTC596
            related_to: upload().1,
411bc1c78b65atagen2026-10-22 07:39 UTC597
            file: None,
411bc1c78b65atagen2026-10-22 07:39 UTC598
            index: 0,
411bc1c78b65atagen2026-10-22 07:39 UTC599
            progress: AbstractProgress {
411bc1c78b65atagen2026-10-22 07:39 UTC600
                current: 1,
411bc1c78b65atagen2026-10-22 07:39 UTC601
                total: 2,
411bc1c78b65atagen2026-10-22 07:39 UTC602
            },
411bc1c78b65atagen2026-10-22 07:39 UTC603
        })
7cf348521204atagen2026-09-26 12:28 UTC604
    }
7cf348521204atagen2026-09-26 12:28 UTC605
411bc1c78b65atagen2026-10-22 07:39 UTC606
    fn sent() -> SendQueueUpdate {
411bc1c78b65atagen2026-10-22 07:39 UTC607
        update(RoomSendQueueUpdate::SentEvent {
411bc1c78b65atagen2026-10-22 07:39 UTC608
            transaction_id: upload().1,
411bc1c78b65atagen2026-10-22 07:39 UTC609
            event_id: event_id!("$sent:localhost").to_owned(),
411bc1c78b65atagen2026-10-22 07:39 UTC610
        })
7cf348521204atagen2026-09-26 12:28 UTC611
    }
7cf348521204atagen2026-09-26 12:28 UTC612
7cf348521204atagen2026-09-26 12:28 UTC613
    fn finished(event: Option<Event>) -> Option<UploadOutcome> {
7cf348521204atagen2026-09-26 12:28 UTC614
        match event? {
7cf348521204atagen2026-09-26 12:28 UTC615
            Event::MediaUploadFinished { outcome, .. } => Some(outcome),
7cf348521204atagen2026-09-26 12:28 UTC616
            _ => None,
7cf348521204atagen2026-09-26 12:28 UTC617
        }
7cf348521204atagen2026-09-26 12:28 UTC618
    }
7c26fad34822atagen2026-09-26 09:41 UTC619
7cf348521204atagen2026-09-26 12:28 UTC620
    #[test]
411bc1c78b65atagen2026-10-22 07:39 UTC621
    fn a_tick_trailing_its_end_says_nothing() {
411bc1c78b65atagen2026-10-22 07:39 UTC622
        let mut tracker = UploadTracker::new(HashSet::new());
411bc1c78b65atagen2026-10-22 07:39 UTC623
        assert!(tracker.update(tick()).is_some());
411bc1c78b65atagen2026-10-22 07:39 UTC624
        assert!(matches!(
411bc1c78b65atagen2026-10-22 07:39 UTC625
            finished(tracker.update(sent())),
411bc1c78b65atagen2026-10-22 07:39 UTC626
            Some(UploadOutcome::Sent { .. })
411bc1c78b65atagen2026-10-22 07:39 UTC627
        ));
411bc1c78b65atagen2026-10-22 07:39 UTC628
        assert!(tracker.update(tick()).is_none());
411bc1c78b65atagen2026-10-22 07:39 UTC629
        assert!(tracker.live.is_empty());
411bc1c78b65atagen2026-10-22 07:39 UTC630
    }
411bc1c78b65atagen2026-10-22 07:39 UTC631
411bc1c78b65atagen2026-10-22 07:39 UTC632
    #[test]
7cf348521204atagen2026-09-26 12:28 UTC633
    fn a_stale_tick_after_a_missed_end_changes_nothing() {
411bc1c78b65atagen2026-10-22 07:39 UTC634
        let mut tracker = UploadTracker::new(HashSet::new());
411bc1c78b65atagen2026-10-22 07:39 UTC635
        assert!(tracker.update(tick()).is_some());
7c26fad34822atagen2026-09-26 09:41 UTC636
        let missed = tracker.resnapshot(HashSet::new());
7c26fad34822atagen2026-09-26 09:41 UTC637
        assert!(matches!(
7c26fad34822atagen2026-09-26 09:41 UTC638
            missed.as_slice(),
7c26fad34822atagen2026-09-26 09:41 UTC639
            [Event::MediaUploadFinished {
7c26fad34822atagen2026-09-26 09:41 UTC640
                outcome: UploadOutcome::Missed,
7c26fad34822atagen2026-09-26 09:41 UTC641
                ..
7c26fad34822atagen2026-09-26 09:41 UTC642
            }]
7c26fad34822atagen2026-09-26 09:41 UTC643
        ));
411bc1c78b65atagen2026-10-22 07:39 UTC644
        assert!(tracker.update(tick()).is_none());
411bc1c78b65atagen2026-10-22 07:39 UTC645
        assert!(tracker.update(sent()).is_none());
411bc1c78b65atagen2026-10-22 07:39 UTC646
        assert!(tracker.live.is_empty());
7c26fad34822atagen2026-09-26 09:41 UTC647
    }
7c26fad34822atagen2026-09-26 09:41 UTC648
}