atagen

macltok

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

Blame: src/engine/watchers.rs

0bfa3f46f0beatagen2026-09-26 09:12 UTC1
use std::{collections::HashSet, sync::Arc, time::Duration};
31ce2453c82fatagen2026-09-24 13:07 UTC2
31ce2453c82fatagen2026-09-24 13:07 UTC3
use futures_util::StreamExt;
31ce2453c82fatagen2026-09-24 13:07 UTC4
use matrix_sdk::{
31ce2453c82fatagen2026-09-24 13:07 UTC5
    Client, Room, SessionChange,
31ce2453c82fatagen2026-09-24 13:07 UTC6
    ruma::events::{AnyMessageLikeEventContent, room::message::MessageType},
0bfa3f46f0beatagen2026-09-26 09:12 UTC7
    send_queue::{LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate},
31ce2453c82fatagen2026-09-24 13:07 UTC8
};
31ce2453c82fatagen2026-09-24 13:07 UTC9
use matrix_sdk_ui::sync_service::{State as SyncState, SyncService};
0bfa3f46f0beatagen2026-09-26 09:12 UTC10
use ruma::{OwnedDeviceId, OwnedRoomId, OwnedTransactionId, time::Instant};
fe4133dbcd47atagen2026-09-26 09:05 UTC11
use tokio::sync::{broadcast::error::RecvError, mpsc, watch};
31ce2453c82fatagen2026-09-24 13:07 UTC12
1fe480c16a3catagen2026-09-26 08:44 UTC13
use super::executor::TaskSet;
31ce2453c82fatagen2026-09-24 13:07 UTC14
use crate::{
0bfa3f46f0beatagen2026-09-26 09:12 UTC15
    ConnectionState, Event, Termination, UploadOutcome, encryption::encryption_state,
0bfa3f46f0beatagen2026-09-26 09:12 UTC16
    error::classify_sdk_error, transport::EventSender,
31ce2453c82fatagen2026-09-24 13:07 UTC17
};
31ce2453c82fatagen2026-09-24 13:07 UTC18
31ce2453c82fatagen2026-09-24 13:07 UTC19
const SYNC_RESTART_MIN: Duration = Duration::from_secs(1);
31ce2453c82fatagen2026-09-24 13:07 UTC20
const SYNC_RESTART_MAX: Duration = Duration::from_secs(60);
31ce2453c82fatagen2026-09-24 13:07 UTC21
const SEND_QUEUE_RETRY: Duration = Duration::from_secs(5);
5a52012c9b1datagen2026-09-24 23:45 UTC22
const SYNC_STABLE: Duration = Duration::from_secs(30);
5a52012c9b1datagen2026-09-24 23:45 UTC23
5a52012c9b1datagen2026-09-24 23:45 UTC24
pub(super) async fn room_subscriptions(
5a52012c9b1datagen2026-09-24 23:45 UTC25
    sync: Arc<SyncService>,
5a52012c9b1datagen2026-09-24 23:45 UTC26
    mut rooms: watch::Receiver<Vec<ruma::OwnedRoomId>>,
5a52012c9b1datagen2026-09-24 23:45 UTC27
) {
5a52012c9b1datagen2026-09-24 23:45 UTC28
    while rooms.changed().await.is_ok() {
5a52012c9b1datagen2026-09-24 23:45 UTC29
        let room_ids = rooms.borrow_and_update().clone();
5a52012c9b1datagen2026-09-24 23:45 UTC30
        let room_ids = room_ids.iter().map(AsRef::as_ref).collect::<Vec<_>>();
5a52012c9b1datagen2026-09-24 23:45 UTC31
        sync.room_list_service().subscribe_to_rooms(&room_ids).await;
5a52012c9b1datagen2026-09-24 23:45 UTC32
    }
5a52012c9b1datagen2026-09-24 23:45 UTC33
}
31ce2453c82fatagen2026-09-24 13:07 UTC34
31ce2453c82fatagen2026-09-24 13:07 UTC35
pub(super) async fn session(
31ce2453c82fatagen2026-09-24 13:07 UTC36
    mut changes: tokio::sync::broadcast::Receiver<SessionChange>,
31ce2453c82fatagen2026-09-24 13:07 UTC37
    events: EventSender,
fe4133dbcd47atagen2026-09-26 09:05 UTC38
    device_id: OwnedDeviceId,
fe4133dbcd47atagen2026-09-26 09:05 UTC39
    stop: mpsc::UnboundedSender<Termination>,
31ce2453c82fatagen2026-09-24 13:07 UTC40
) {
31ce2453c82fatagen2026-09-24 13:07 UTC41
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC42
        let event = match changes.recv().await {
31ce2453c82fatagen2026-09-24 13:07 UTC43
            Ok(SessionChange::TokensRefreshed) => Event::SessionTokensChanged,
31ce2453c82fatagen2026-09-24 13:07 UTC44
            Ok(SessionChange::UnknownToken(data)) => {
7c26fad34822atagen2026-09-26 09:41 UTC45
                let soft_logout = data.soft_logout.then_some(device_id);
31ce2453c82fatagen2026-09-24 13:07 UTC46
                let _ = events
31ce2453c82fatagen2026-09-24 13:07 UTC47
                    .send(Event::SessionAccessRejected {
7c26fad34822atagen2026-09-26 09:41 UTC48
                        soft_logout: soft_logout.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC49
                    })
31ce2453c82fatagen2026-09-24 13:07 UTC50
                    .await;
7c26fad34822atagen2026-09-26 09:41 UTC51
                let _ = stop.send(match soft_logout {
7c26fad34822atagen2026-09-26 09:41 UTC52
                    Some(device_id) => Termination::SoftLoggedOut { device_id },
7c26fad34822atagen2026-09-26 09:41 UTC53
                    None => Termination::AccessRevoked,
fe4133dbcd47atagen2026-09-26 09:05 UTC54
                });
31ce2453c82fatagen2026-09-24 13:07 UTC55
                return;
31ce2453c82fatagen2026-09-24 13:07 UTC56
            }
31ce2453c82fatagen2026-09-24 13:07 UTC57
            // a missed refresh costs one needless save, a missed rejection comes round again
31ce2453c82fatagen2026-09-24 13:07 UTC58
            Err(RecvError::Lagged(_)) => Event::SessionTokensChanged,
31ce2453c82fatagen2026-09-24 13:07 UTC59
            Err(RecvError::Closed) => return,
31ce2453c82fatagen2026-09-24 13:07 UTC60
        };
31ce2453c82fatagen2026-09-24 13:07 UTC61
        if events.send(event).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC62
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC63
        }
31ce2453c82fatagen2026-09-24 13:07 UTC64
    }
31ce2453c82fatagen2026-09-24 13:07 UTC65
}
31ce2453c82fatagen2026-09-24 13:07 UTC66
31ce2453c82fatagen2026-09-24 13:07 UTC67
/// `states` must be taken before sync starts, a late subscriber never hears the transition it missed
31ce2453c82fatagen2026-09-24 13:07 UTC68
pub(super) async fn connection(
31ce2453c82fatagen2026-09-24 13:07 UTC69
    mut states: impl futures_util::Stream<Item = SyncState> + Unpin,
31ce2453c82fatagen2026-09-24 13:07 UTC70
    sync: Arc<SyncService>,
31ce2453c82fatagen2026-09-24 13:07 UTC71
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC72
    events: EventSender,
31ce2453c82fatagen2026-09-24 13:07 UTC73
    connection: watch::Sender<ConnectionState>,
31ce2453c82fatagen2026-09-24 13:07 UTC74
) {
31ce2453c82fatagen2026-09-24 13:07 UTC75
    let mut backoff = SYNC_RESTART_MIN;
5a52012c9b1datagen2026-09-24 23:45 UTC76
    let mut online_since: Option<Instant> = None;
31ce2453c82fatagen2026-09-24 13:07 UTC77
    while let Some(state) = states.next().await {
5a52012c9b1datagen2026-09-24 23:45 UTC78
        // only a run that lasted counts as recovered, or a server that answers /versions
5a52012c9b1datagen2026-09-24 23:45 UTC79
        // but refuses sync would have us bounce between offline and online forever
5a52012c9b1datagen2026-09-24 23:45 UTC80
        let stable = online_since
5a52012c9b1datagen2026-09-24 23:45 UTC81
            .take()
5a52012c9b1datagen2026-09-24 23:45 UTC82
            .map(|since| since.elapsed() >= SYNC_STABLE);
5a52012c9b1datagen2026-09-24 23:45 UTC83
        if stable == Some(true) {
5a52012c9b1datagen2026-09-24 23:45 UTC84
            backoff = SYNC_RESTART_MIN;
5a52012c9b1datagen2026-09-24 23:45 UTC85
        }
31ce2453c82fatagen2026-09-24 13:07 UTC86
        let (state, restart) = match state {
5a52012c9b1datagen2026-09-24 23:45 UTC87
            // only ever us stopping it for a restart, nothing a client needs to hear
5a52012c9b1datagen2026-09-24 23:45 UTC88
            SyncState::Idle => continue,
31ce2453c82fatagen2026-09-24 13:07 UTC89
            SyncState::Running => {
5a52012c9b1datagen2026-09-24 23:45 UTC90
                online_since = Some(Instant::now());
31ce2453c82fatagen2026-09-24 13:07 UTC91
                // the sdk parks a room queue on any send error and never unparks it
31ce2453c82fatagen2026-09-24 13:07 UTC92
                client.send_queue().set_enabled(true).await;
31ce2453c82fatagen2026-09-24 13:07 UTC93
                (ConnectionState::Online, false)
31ce2453c82fatagen2026-09-24 13:07 UTC94
            }
5a52012c9b1datagen2026-09-24 23:45 UTC95
            SyncState::Offline => (ConnectionState::Offline, stable == Some(false)),
31ce2453c82fatagen2026-09-24 13:07 UTC96
            SyncState::Terminated => (ConnectionState::Offline, true),
31ce2453c82fatagen2026-09-24 13:07 UTC97
            SyncState::Error(error) => {
31ce2453c82fatagen2026-09-24 13:07 UTC98
                tracing::warn!(%error, "sync service reported an error");
31ce2453c82fatagen2026-09-24 13:07 UTC99
                (ConnectionState::Offline, true)
31ce2453c82fatagen2026-09-24 13:07 UTC100
            }
31ce2453c82fatagen2026-09-24 13:07 UTC101
        };
31ce2453c82fatagen2026-09-24 13:07 UTC102
        if *connection.borrow() != state {
31ce2453c82fatagen2026-09-24 13:07 UTC103
            connection.send_replace(state);
31ce2453c82fatagen2026-09-24 13:07 UTC104
            if events.send(Event::ConnectionChanged(state)).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC105
                return;
31ce2453c82fatagen2026-09-24 13:07 UTC106
            }
31ce2453c82fatagen2026-09-24 13:07 UTC107
        }
31ce2453c82fatagen2026-09-24 13:07 UTC108
        if restart {
5a52012c9b1datagen2026-09-24 23:45 UTC109
            sync.stop().await;
1fe480c16a3catagen2026-09-26 08:44 UTC110
            matrix_sdk::sleep::sleep(backoff).await;
31ce2453c82fatagen2026-09-24 13:07 UTC111
            backoff = (backoff * 2).min(SYNC_RESTART_MAX);
31ce2453c82fatagen2026-09-24 13:07 UTC112
            sync.start().await;
31ce2453c82fatagen2026-09-24 13:07 UTC113
        }
31ce2453c82fatagen2026-09-24 13:07 UTC114
    }
31ce2453c82fatagen2026-09-24 13:07 UTC115
}
31ce2453c82fatagen2026-09-24 13:07 UTC116
31ce2453c82fatagen2026-09-24 13:07 UTC117
/// a recoverable failure while we're online is a hiccup, so give the room another go
31ce2453c82fatagen2026-09-24 13:07 UTC118
pub(super) async fn send_queue_errors(
31ce2453c82fatagen2026-09-24 13:07 UTC119
    client: Client,
31ce2453c82fatagen2026-09-24 13:07 UTC120
    mut errors: tokio::sync::broadcast::Receiver<matrix_sdk::send_queue::SendQueueRoomError>,
31ce2453c82fatagen2026-09-24 13:07 UTC121
    online: watch::Receiver<ConnectionState>,
31ce2453c82fatagen2026-09-24 13:07 UTC122
) {
1fe480c16a3catagen2026-09-26 08:44 UTC123
    let mut retries = TaskSet::new();
31ce2453c82fatagen2026-09-24 13:07 UTC124
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC125
        let error = tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC126
            error = errors.recv() => error,
31ce2453c82fatagen2026-09-24 13:07 UTC127
            Some(_) = retries.join_next(), if !retries.is_empty() => continue,
31ce2453c82fatagen2026-09-24 13:07 UTC128
        };
31ce2453c82fatagen2026-09-24 13:07 UTC129
        match error {
31ce2453c82fatagen2026-09-24 13:07 UTC130
            Ok(error) if error.is_recoverable => {
31ce2453c82fatagen2026-09-24 13:07 UTC131
                let client = client.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC132
                let online = online.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC133
                retries.spawn(async move {
1fe480c16a3catagen2026-09-26 08:44 UTC134
                    matrix_sdk::sleep::sleep(SEND_QUEUE_RETRY).await;
31ce2453c82fatagen2026-09-24 13:07 UTC135
                    if *online.borrow() == ConnectionState::Online
31ce2453c82fatagen2026-09-24 13:07 UTC136
                        && let Some(room) = client.get_room(&error.room_id)
31ce2453c82fatagen2026-09-24 13:07 UTC137
                    {
31ce2453c82fatagen2026-09-24 13:07 UTC138
                        room.send_queue().set_enabled(true);
31ce2453c82fatagen2026-09-24 13:07 UTC139
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC140
                });
31ce2453c82fatagen2026-09-24 13:07 UTC141
            }
31ce2453c82fatagen2026-09-24 13:07 UTC142
            Ok(_) | Err(RecvError::Lagged(_)) => {}
31ce2453c82fatagen2026-09-24 13:07 UTC143
            Err(RecvError::Closed) => return,
31ce2453c82fatagen2026-09-24 13:07 UTC144
        }
31ce2453c82fatagen2026-09-24 13:07 UTC145
    }
31ce2453c82fatagen2026-09-24 13:07 UTC146
}
31ce2453c82fatagen2026-09-24 13:07 UTC147
31ce2453c82fatagen2026-09-24 13:07 UTC148
/// upload progress only goes out on the room's own channel, never the client-wide one
7c26fad34822atagen2026-09-26 09:41 UTC149
pub(super) async fn room_uploads(
7c26fad34822atagen2026-09-26 09:41 UTC150
    room: Room,
7c26fad34822atagen2026-09-26 09:41 UTC151
    progress: mpsc::Sender<UploadProgress>,
7c26fad34822atagen2026-09-26 09:41 UTC152
    ready: watch::Sender<bool>,
7c26fad34822atagen2026-09-26 09:41 UTC153
) {
31ce2453c82fatagen2026-09-24 13:07 UTC154
    let room_id = room.room_id().to_owned();
31ce2453c82fatagen2026-09-24 13:07 UTC155
    let mut updates = match room.send_queue().subscribe().await {
31ce2453c82fatagen2026-09-24 13:07 UTC156
        Ok((_, updates)) => updates,
31ce2453c82fatagen2026-09-24 13:07 UTC157
        Err(error) => {
31ce2453c82fatagen2026-09-24 13:07 UTC158
            tracing::warn!(%room_id, %error, "reading the media send queue failed");
31ce2453c82fatagen2026-09-24 13:07 UTC159
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC160
        }
31ce2453c82fatagen2026-09-24 13:07 UTC161
    };
31ce2453c82fatagen2026-09-24 13:07 UTC162
    ready.send_replace(true);
31ce2453c82fatagen2026-09-24 13:07 UTC163
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC164
        let update = match updates.recv().await {
31ce2453c82fatagen2026-09-24 13:07 UTC165
            Ok(update) => update,
5a52012c9b1datagen2026-09-24 23:45 UTC166
            // a missed tick is fine, the next one says where it's got to
5a52012c9b1datagen2026-09-24 23:45 UTC167
            Err(RecvError::Lagged(_)) => continue,
5a52012c9b1datagen2026-09-24 23:45 UTC168
            Err(RecvError::Closed) => return,
5a52012c9b1datagen2026-09-24 23:45 UTC169
        };
5a52012c9b1datagen2026-09-24 23:45 UTC170
        let RoomSendQueueUpdate::MediaUpload {
5a52012c9b1datagen2026-09-24 23:45 UTC171
            related_to,
5a52012c9b1datagen2026-09-24 23:45 UTC172
            file,
7c26fad34822atagen2026-09-26 09:41 UTC173
            progress: done,
5a52012c9b1datagen2026-09-24 23:45 UTC174
            ..
5a52012c9b1datagen2026-09-24 23:45 UTC175
        } = update
5a52012c9b1datagen2026-09-24 23:45 UTC176
        else {
5a52012c9b1datagen2026-09-24 23:45 UTC177
            continue;
5a52012c9b1datagen2026-09-24 23:45 UTC178
        };
7c26fad34822atagen2026-09-26 09:41 UTC179
        let tick = UploadProgress {
7c26fad34822atagen2026-09-26 09:41 UTC180
            upload: (room_id.clone(), related_to),
7c26fad34822atagen2026-09-26 09:41 UTC181
            uploaded_bytes: done.current as u64,
7c26fad34822atagen2026-09-26 09:41 UTC182
            total_bytes: done.total as u64,
7c26fad34822atagen2026-09-26 09:41 UTC183
            complete: file.is_some() && done.current == done.total,
5a52012c9b1datagen2026-09-24 23:45 UTC184
        };
7c26fad34822atagen2026-09-26 09:41 UTC185
        if progress.send(tick).await.is_err() {
5a52012c9b1datagen2026-09-24 23:45 UTC186
            return;
5a52012c9b1datagen2026-09-24 23:45 UTC187
        }
5a52012c9b1datagen2026-09-24 23:45 UTC188
    }
5a52012c9b1datagen2026-09-24 23:45 UTC189
}
5a52012c9b1datagen2026-09-24 23:45 UTC190
7c26fad34822atagen2026-09-26 09:41 UTC191
pub(super) struct UploadProgress {
7c26fad34822atagen2026-09-26 09:41 UTC192
    upload: Upload,
7c26fad34822atagen2026-09-26 09:41 UTC193
    uploaded_bytes: u64,
7c26fad34822atagen2026-09-26 09:41 UTC194
    total_bytes: u64,
7c26fad34822atagen2026-09-26 09:41 UTC195
    complete: bool,
7c26fad34822atagen2026-09-26 09:41 UTC196
}
7c26fad34822atagen2026-09-26 09:41 UTC197
7c26fad34822atagen2026-09-26 09:41 UTC198
/// the one place upload events leave from, so an upload is never reported after it
7c26fad34822atagen2026-09-26 09:41 UTC199
/// ended. progress comes in from the room forwarders, the rest from the client-wide
7c26fad34822atagen2026-09-26 09:41 UTC200
/// channel, which exists before any upload does
0bfa3f46f0beatagen2026-09-26 09:12 UTC201
pub(super) async fn uploads(
5a52012c9b1datagen2026-09-24 23:45 UTC202
    client: Client,
0bfa3f46f0beatagen2026-09-26 09:12 UTC203
    mut updates: tokio::sync::broadcast::Receiver<SendQueueUpdate>,
7c26fad34822atagen2026-09-26 09:41 UTC204
    mut progress: mpsc::Receiver<UploadProgress>,
5a52012c9b1datagen2026-09-24 23:45 UTC205
    events: EventSender,
5a52012c9b1datagen2026-09-24 23:45 UTC206
) {
0bfa3f46f0beatagen2026-09-26 09:12 UTC207
    let (_, mut rooms) = client.rooms_stream();
7c26fad34822atagen2026-09-26 09:41 UTC208
    let mut tracker = UploadTracker {
7c26fad34822atagen2026-09-26 09:41 UTC209
        live: attachment_echoes(&client).await,
7c26fad34822atagen2026-09-26 09:41 UTC210
        ended: HashSet::new(),
7c26fad34822atagen2026-09-26 09:41 UTC211
    };
5a52012c9b1datagen2026-09-24 23:45 UTC212
    loop {
7c26fad34822atagen2026-09-26 09:41 UTC213
        let reports = tokio::select! {
0bfa3f46f0beatagen2026-09-26 09:12 UTC214
            update = updates.recv() => match update {
7c26fad34822atagen2026-09-26 09:41 UTC215
                Ok(update) => tracker.update(update).into_iter().collect(),
0bfa3f46f0beatagen2026-09-26 09:12 UTC216
                Err(RecvError::Lagged(skipped)) => {
0bfa3f46f0beatagen2026-09-26 09:12 UTC217
                    tracing::warn!(skipped, "upload watcher lagged");
0bfa3f46f0beatagen2026-09-26 09:12 UTC218
                    let current = attachment_echoes(&client).await;
7c26fad34822atagen2026-09-26 09:41 UTC219
                    tracker.resnapshot(current)
0bfa3f46f0beatagen2026-09-26 09:12 UTC220
                }
0bfa3f46f0beatagen2026-09-26 09:12 UTC221
                Err(RecvError::Closed) => return,
0bfa3f46f0beatagen2026-09-26 09:12 UTC222
            },
7c26fad34822atagen2026-09-26 09:41 UTC223
            Some(tick) = progress.recv() => tracker.progress(tick).into_iter().collect(),
0bfa3f46f0beatagen2026-09-26 09:12 UTC224
            update = rooms.next() => {
0bfa3f46f0beatagen2026-09-26 09:12 UTC225
                if update.is_none() {
0bfa3f46f0beatagen2026-09-26 09:12 UTC226
                    return;
0bfa3f46f0beatagen2026-09-26 09:12 UTC227
                }
7c26fad34822atagen2026-09-26 09:41 UTC228
                tracker.finish_where(
7c26fad34822atagen2026-09-26 09:41 UTC229
                    |(room_id, _)| client.get_room(room_id).is_none(),
7c26fad34822atagen2026-09-26 09:41 UTC230
                    &UploadOutcome::RoomForgotten,
7c26fad34822atagen2026-09-26 09:41 UTC231
                )
31ce2453c82fatagen2026-09-24 13:07 UTC232
            }
31ce2453c82fatagen2026-09-24 13:07 UTC233
        };
7c26fad34822atagen2026-09-26 09:41 UTC234
        for event in reports {
0bfa3f46f0beatagen2026-09-26 09:12 UTC235
            if events.send(event).await.is_err() {
0bfa3f46f0beatagen2026-09-26 09:12 UTC236
                return;
0bfa3f46f0beatagen2026-09-26 09:12 UTC237
            }
0bfa3f46f0beatagen2026-09-26 09:12 UTC238
        }
0bfa3f46f0beatagen2026-09-26 09:12 UTC239
    }
0bfa3f46f0beatagen2026-09-26 09:12 UTC240
}
0bfa3f46f0beatagen2026-09-26 09:12 UTC241
0bfa3f46f0beatagen2026-09-26 09:12 UTC242
type Upload = (OwnedRoomId, OwnedTransactionId);
0bfa3f46f0beatagen2026-09-26 09:12 UTC243
7c26fad34822atagen2026-09-26 09:41 UTC244
/// everything reported gets exactly one `MediaUploadFinished`. `ended` is kept for good,
7c26fad34822atagen2026-09-26 09:41 UTC245
/// since a room forwarder can still be holding progress for an upload the client-wide
7c26fad34822atagen2026-09-26 09:41 UTC246
/// channel has already seen sent
7c26fad34822atagen2026-09-26 09:41 UTC247
struct UploadTracker {
7c26fad34822atagen2026-09-26 09:41 UTC248
    live: HashSet<Upload>,
7c26fad34822atagen2026-09-26 09:41 UTC249
    ended: HashSet<Upload>,
0bfa3f46f0beatagen2026-09-26 09:12 UTC250
}
0bfa3f46f0beatagen2026-09-26 09:12 UTC251
7c26fad34822atagen2026-09-26 09:41 UTC252
impl UploadTracker {
7c26fad34822atagen2026-09-26 09:41 UTC253
    fn update(&mut self, update: SendQueueUpdate) -> Option<Event> {
7c26fad34822atagen2026-09-26 09:41 UTC254
        let room_id = update.room_id;
7c26fad34822atagen2026-09-26 09:41 UTC255
        let (transaction_id, outcome) = match update.update {
7c26fad34822atagen2026-09-26 09:41 UTC256
            RoomSendQueueUpdate::NewLocalEvent(echo) => {
7c26fad34822atagen2026-09-26 09:41 UTC257
                let upload = (room_id, echo.transaction_id);
7c26fad34822atagen2026-09-26 09:41 UTC258
                if is_attachment_echo(&echo.content) && !self.ended.contains(&upload) {
7c26fad34822atagen2026-09-26 09:41 UTC259
                    self.live.insert(upload);
7c26fad34822atagen2026-09-26 09:41 UTC260
                }
0bfa3f46f0beatagen2026-09-26 09:12 UTC261
                return None;
0bfa3f46f0beatagen2026-09-26 09:12 UTC262
            }
7c26fad34822atagen2026-09-26 09:41 UTC263
            RoomSendQueueUpdate::SendError {
0bfa3f46f0beatagen2026-09-26 09:12 UTC264
                transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC265
                error,
7c26fad34822atagen2026-09-26 09:41 UTC266
                is_recoverable,
7c26fad34822atagen2026-09-26 09:41 UTC267
            } => {
7c26fad34822atagen2026-09-26 09:41 UTC268
                let upload = (room_id, transaction_id);
7c26fad34822atagen2026-09-26 09:41 UTC269
                if !self.live.contains(&upload) {
7c26fad34822atagen2026-09-26 09:41 UTC270
                    return None;
7c26fad34822atagen2026-09-26 09:41 UTC271
                }
7c26fad34822atagen2026-09-26 09:41 UTC272
                let (room_id, transaction_id) = upload;
7c26fad34822atagen2026-09-26 09:41 UTC273
                return Some(Event::MediaUploadFailed {
7c26fad34822atagen2026-09-26 09:41 UTC274
                    room_id,
7c26fad34822atagen2026-09-26 09:41 UTC275
                    transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC276
                    kind: classify_sdk_error(&error),
7c26fad34822atagen2026-09-26 09:41 UTC277
                    will_retry: is_recoverable,
7c26fad34822atagen2026-09-26 09:41 UTC278
                });
7c26fad34822atagen2026-09-26 09:41 UTC279
            }
7c26fad34822atagen2026-09-26 09:41 UTC280
            RoomSendQueueUpdate::SentEvent {
7c26fad34822atagen2026-09-26 09:41 UTC281
                transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC282
                event_id,
7c26fad34822atagen2026-09-26 09:41 UTC283
            } => (transaction_id, UploadOutcome::Sent { event_id }),
7c26fad34822atagen2026-09-26 09:41 UTC284
            RoomSendQueueUpdate::CancelledLocalEvent { transaction_id } => {
7c26fad34822atagen2026-09-26 09:41 UTC285
                (transaction_id, UploadOutcome::Cancelled)
7c26fad34822atagen2026-09-26 09:41 UTC286
            }
7c26fad34822atagen2026-09-26 09:41 UTC287
            _ => return None,
7c26fad34822atagen2026-09-26 09:41 UTC288
        };
7c26fad34822atagen2026-09-26 09:41 UTC289
        self.finish((room_id, transaction_id), outcome)
7c26fad34822atagen2026-09-26 09:41 UTC290
    }
7c26fad34822atagen2026-09-26 09:41 UTC291
7c26fad34822atagen2026-09-26 09:41 UTC292
    fn progress(&mut self, tick: UploadProgress) -> Option<Event> {
7c26fad34822atagen2026-09-26 09:41 UTC293
        if self.ended.contains(&tick.upload) {
7c26fad34822atagen2026-09-26 09:41 UTC294
            return None;
5a52012c9b1datagen2026-09-24 23:45 UTC295
        }
7c26fad34822atagen2026-09-26 09:41 UTC296
        self.live.insert(tick.upload.clone());
7c26fad34822atagen2026-09-26 09:41 UTC297
        let (room_id, transaction_id) = tick.upload;
7c26fad34822atagen2026-09-26 09:41 UTC298
        Some(Event::MediaUploadProgress {
7c26fad34822atagen2026-09-26 09:41 UTC299
            room_id,
5a52012c9b1datagen2026-09-24 23:45 UTC300
            transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC301
            uploaded_bytes: tick.uploaded_bytes,
7c26fad34822atagen2026-09-26 09:41 UTC302
            total_bytes: tick.total_bytes,
7c26fad34822atagen2026-09-26 09:41 UTC303
            complete: tick.complete,
7c26fad34822atagen2026-09-26 09:41 UTC304
        })
7c26fad34822atagen2026-09-26 09:41 UTC305
    }
7c26fad34822atagen2026-09-26 09:41 UTC306
7c26fad34822atagen2026-09-26 09:41 UTC307
    fn resnapshot(&mut self, current: HashSet<Upload>) -> Vec<Event> {
7c26fad34822atagen2026-09-26 09:41 UTC308
        let reports = self.finish_where(|upload| !current.contains(upload), &UploadOutcome::Missed);
7c26fad34822atagen2026-09-26 09:41 UTC309
        let ended = &self.ended;
7c26fad34822atagen2026-09-26 09:41 UTC310
        self.live
7c26fad34822atagen2026-09-26 09:41 UTC311
            .extend(current.into_iter().filter(|upload| !ended.contains(upload)));
7c26fad34822atagen2026-09-26 09:41 UTC312
        reports
7c26fad34822atagen2026-09-26 09:41 UTC313
    }
7c26fad34822atagen2026-09-26 09:41 UTC314
7c26fad34822atagen2026-09-26 09:41 UTC315
    fn finish_where(
7c26fad34822atagen2026-09-26 09:41 UTC316
        &mut self,
7c26fad34822atagen2026-09-26 09:41 UTC317
        ends: impl Fn(&Upload) -> bool,
7c26fad34822atagen2026-09-26 09:41 UTC318
        outcome: &UploadOutcome,
7c26fad34822atagen2026-09-26 09:41 UTC319
    ) -> Vec<Event> {
7c26fad34822atagen2026-09-26 09:41 UTC320
        let ending = self
7c26fad34822atagen2026-09-26 09:41 UTC321
            .live
7c26fad34822atagen2026-09-26 09:41 UTC322
            .iter()
7c26fad34822atagen2026-09-26 09:41 UTC323
            .filter(|upload| ends(upload))
7c26fad34822atagen2026-09-26 09:41 UTC324
            .cloned()
7c26fad34822atagen2026-09-26 09:41 UTC325
            .collect::<Vec<_>>();
7c26fad34822atagen2026-09-26 09:41 UTC326
        ending
7c26fad34822atagen2026-09-26 09:41 UTC327
            .into_iter()
7c26fad34822atagen2026-09-26 09:41 UTC328
            .filter_map(|upload| self.finish(upload, outcome.clone()))
7c26fad34822atagen2026-09-26 09:41 UTC329
            .collect()
7c26fad34822atagen2026-09-26 09:41 UTC330
    }
7c26fad34822atagen2026-09-26 09:41 UTC331
7c26fad34822atagen2026-09-26 09:41 UTC332
    fn finish(&mut self, upload: Upload, outcome: UploadOutcome) -> Option<Event> {
7c26fad34822atagen2026-09-26 09:41 UTC333
        if !self.live.remove(&upload) {
7c26fad34822atagen2026-09-26 09:41 UTC334
            return None;
31ce2453c82fatagen2026-09-24 13:07 UTC335
        }
7c26fad34822atagen2026-09-26 09:41 UTC336
        self.ended.insert(upload.clone());
7c26fad34822atagen2026-09-26 09:41 UTC337
        let (room_id, transaction_id) = upload;
7c26fad34822atagen2026-09-26 09:41 UTC338
        Some(Event::MediaUploadFinished {
7c26fad34822atagen2026-09-26 09:41 UTC339
            room_id,
7c26fad34822atagen2026-09-26 09:41 UTC340
            transaction_id,
7c26fad34822atagen2026-09-26 09:41 UTC341
            outcome,
7c26fad34822atagen2026-09-26 09:41 UTC342
        })
31ce2453c82fatagen2026-09-24 13:07 UTC343
    }
0bfa3f46f0beatagen2026-09-26 09:12 UTC344
}
0bfa3f46f0beatagen2026-09-26 09:12 UTC345
7c26fad34822atagen2026-09-26 09:41 UTC346
async fn attachment_echoes(client: &Client) -> HashSet<Upload> {
7c26fad34822atagen2026-09-26 09:41 UTC347
    let Ok(echoes) = client.send_queue().local_echoes().await else {
7c26fad34822atagen2026-09-26 09:41 UTC348
        return HashSet::new();
7c26fad34822atagen2026-09-26 09:41 UTC349
    };
7c26fad34822atagen2026-09-26 09:41 UTC350
    echoes
0bfa3f46f0beatagen2026-09-26 09:12 UTC351
        .into_iter()
7c26fad34822atagen2026-09-26 09:41 UTC352
        .flat_map(|(room_id, echoes)| {
7c26fad34822atagen2026-09-26 09:41 UTC353
            echoes
7c26fad34822atagen2026-09-26 09:41 UTC354
                .into_iter()
7c26fad34822atagen2026-09-26 09:41 UTC355
                .filter(|echo| is_attachment_echo(&echo.content))
7c26fad34822atagen2026-09-26 09:41 UTC356
                .map(move |echo| (room_id.clone(), echo.transaction_id))
0bfa3f46f0beatagen2026-09-26 09:12 UTC357
        })
0bfa3f46f0beatagen2026-09-26 09:12 UTC358
        .collect()
31ce2453c82fatagen2026-09-24 13:07 UTC359
}
31ce2453c82fatagen2026-09-24 13:07 UTC360
31ce2453c82fatagen2026-09-24 13:07 UTC361
fn is_attachment_echo(content: &LocalEchoContent) -> bool {
31ce2453c82fatagen2026-09-24 13:07 UTC362
    let LocalEchoContent::Event {
31ce2453c82fatagen2026-09-24 13:07 UTC363
        serialized_event, ..
31ce2453c82fatagen2026-09-24 13:07 UTC364
    } = content
31ce2453c82fatagen2026-09-24 13:07 UTC365
    else {
31ce2453c82fatagen2026-09-24 13:07 UTC366
        return false;
31ce2453c82fatagen2026-09-24 13:07 UTC367
    };
31ce2453c82fatagen2026-09-24 13:07 UTC368
    matches!(
31ce2453c82fatagen2026-09-24 13:07 UTC369
        serialized_event.deserialize(),
31ce2453c82fatagen2026-09-24 13:07 UTC370
        Ok(AnyMessageLikeEventContent::RoomMessage(content))
31ce2453c82fatagen2026-09-24 13:07 UTC371
            if matches!(
31ce2453c82fatagen2026-09-24 13:07 UTC372
                content.msgtype,
31ce2453c82fatagen2026-09-24 13:07 UTC373
                MessageType::Audio(_) | MessageType::File(_) | MessageType::Image(_) | MessageType::Video(_)
31ce2453c82fatagen2026-09-24 13:07 UTC374
            )
31ce2453c82fatagen2026-09-24 13:07 UTC375
    )
31ce2453c82fatagen2026-09-24 13:07 UTC376
}
31ce2453c82fatagen2026-09-24 13:07 UTC377
31ce2453c82fatagen2026-09-24 13:07 UTC378
pub(super) async fn encryption(client: Client, events: EventSender) {
31ce2453c82fatagen2026-09-24 13:07 UTC379
    let Some(device_id) = client.device_id().map(ToOwned::to_owned) else {
31ce2453c82fatagen2026-09-24 13:07 UTC380
        tracing::warn!("encryption watcher stopped because the client has no device id");
31ce2453c82fatagen2026-09-24 13:07 UTC381
        return;
31ce2453c82fatagen2026-09-24 13:07 UTC382
    };
31ce2453c82fatagen2026-09-24 13:07 UTC383
    let recovery = client.encryption().recovery();
31ce2453c82fatagen2026-09-24 13:07 UTC384
    let backups = client.encryption().backups();
31ce2453c82fatagen2026-09-24 13:07 UTC385
    let mut recovery_stream = recovery.state_stream();
31ce2453c82fatagen2026-09-24 13:07 UTC386
    let mut backup_stream = backups.state_stream();
31ce2453c82fatagen2026-09-24 13:07 UTC387
    let mut verification_stream = client.encryption().verification_state();
31ce2453c82fatagen2026-09-24 13:07 UTC388
    let mut recovery_state = recovery.state();
31ce2453c82fatagen2026-09-24 13:07 UTC389
    let mut backup_state = backups.state();
31ce2453c82fatagen2026-09-24 13:07 UTC390
    let mut verification_state = verification_stream.get();
31ce2453c82fatagen2026-09-24 13:07 UTC391
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC392
        let state = encryption_state(
31ce2453c82fatagen2026-09-24 13:07 UTC393
            device_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC394
            recovery_state,
31ce2453c82fatagen2026-09-24 13:07 UTC395
            verification_state,
31ce2453c82fatagen2026-09-24 13:07 UTC396
            backup_state,
31ce2453c82fatagen2026-09-24 13:07 UTC397
        );
31ce2453c82fatagen2026-09-24 13:07 UTC398
        if events.send(Event::EncryptionChanged(state)).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC399
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC400
        }
31ce2453c82fatagen2026-09-24 13:07 UTC401
        tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC402
            Some(update) = recovery_stream.next() => recovery_state = update,
31ce2453c82fatagen2026-09-24 13:07 UTC403
            Some(update) = verification_stream.next() => verification_state = update,
31ce2453c82fatagen2026-09-24 13:07 UTC404
            Some(update) = backup_stream.next() => {
31ce2453c82fatagen2026-09-24 13:07 UTC405
                backup_state = update.unwrap_or_else(|_| backups.state());
31ce2453c82fatagen2026-09-24 13:07 UTC406
            }
31ce2453c82fatagen2026-09-24 13:07 UTC407
            else => return,
31ce2453c82fatagen2026-09-24 13:07 UTC408
        }
31ce2453c82fatagen2026-09-24 13:07 UTC409
    }
31ce2453c82fatagen2026-09-24 13:07 UTC410
}
31ce2453c82fatagen2026-09-24 13:07 UTC411
31ce2453c82fatagen2026-09-24 13:07 UTC412
pub(super) async fn rooms(client: Client, events: EventSender) {
31ce2453c82fatagen2026-09-24 13:07 UTC413
    let (_, mut rooms) = client.rooms_stream();
31ce2453c82fatagen2026-09-24 13:07 UTC414
    let mut info = client.room_info_notable_update_receiver();
31ce2453c82fatagen2026-09-24 13:07 UTC415
    loop {
31ce2453c82fatagen2026-09-24 13:07 UTC416
        if events.send(Event::RoomsChanged).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC417
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC418
        }
31ce2453c82fatagen2026-09-24 13:07 UTC419
        tokio::select! {
31ce2453c82fatagen2026-09-24 13:07 UTC420
            update = rooms.next() => if update.is_none() { return },
31ce2453c82fatagen2026-09-24 13:07 UTC421
            update = info.recv() => if matches!(update, Err(RecvError::Closed)) { return },
31ce2453c82fatagen2026-09-24 13:07 UTC422
        }
31ce2453c82fatagen2026-09-24 13:07 UTC423
        // a sync touching fifty rooms is one invalidation, not fifty
31ce2453c82fatagen2026-09-24 13:07 UTC424
        while let Ok(_) | Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) =
31ce2453c82fatagen2026-09-24 13:07 UTC425
            info.try_recv()
31ce2453c82fatagen2026-09-24 13:07 UTC426
        {}
31ce2453c82fatagen2026-09-24 13:07 UTC427
    }
31ce2453c82fatagen2026-09-24 13:07 UTC428
}
31ce2453c82fatagen2026-09-24 13:07 UTC429
31ce2453c82fatagen2026-09-24 13:07 UTC430
pub(super) async fn notification_settings(client: Client, events: EventSender) {
31ce2453c82fatagen2026-09-24 13:07 UTC431
    let settings = client.notification_settings().await;
31ce2453c82fatagen2026-09-24 13:07 UTC432
    let mut changes = settings.subscribe_to_changes();
31ce2453c82fatagen2026-09-24 13:07 UTC433
    while let Ok(()) | Err(RecvError::Lagged(_)) = changes.recv().await {
0bfa3f46f0beatagen2026-09-26 09:12 UTC434
        // room summaries carry the effective mode, and push rule changes never touch room info
0bfa3f46f0beatagen2026-09-26 09:12 UTC435
        for event in [Event::NotificationSettingsChanged, Event::RoomsChanged] {
0bfa3f46f0beatagen2026-09-26 09:12 UTC436
            if events.send(event).await.is_err() {
0bfa3f46f0beatagen2026-09-26 09:12 UTC437
                return;
0bfa3f46f0beatagen2026-09-26 09:12 UTC438
            }
31ce2453c82fatagen2026-09-24 13:07 UTC439
        }
31ce2453c82fatagen2026-09-24 13:07 UTC440
    }
31ce2453c82fatagen2026-09-24 13:07 UTC441
}
7c26fad34822atagen2026-09-26 09:41 UTC442
7c26fad34822atagen2026-09-26 09:41 UTC443
#[cfg(test)]
7c26fad34822atagen2026-09-26 09:41 UTC444
mod tests {
7c26fad34822atagen2026-09-26 09:41 UTC445
    use matrix_sdk::send_queue::{RoomSendQueueUpdate, SendQueueUpdate};
7c26fad34822atagen2026-09-26 09:41 UTC446
    use ruma::{OwnedTransactionId, event_id, owned_room_id};
7c26fad34822atagen2026-09-26 09:41 UTC447
7c26fad34822atagen2026-09-26 09:41 UTC448
    use super::{HashSet, UploadProgress, UploadTracker};
7c26fad34822atagen2026-09-26 09:41 UTC449
    use crate::{Event, UploadOutcome};
7c26fad34822atagen2026-09-26 09:41 UTC450
7c26fad34822atagen2026-09-26 09:41 UTC451
    #[test]
7c26fad34822atagen2026-09-26 09:41 UTC452
    fn an_upload_only_progress_saw_still_ends_once() {
7c26fad34822atagen2026-09-26 09:41 UTC453
        let upload = (
7c26fad34822atagen2026-09-26 09:41 UTC454
            owned_room_id!("!room:localhost"),
7c26fad34822atagen2026-09-26 09:41 UTC455
            OwnedTransactionId::from("upload"),
7c26fad34822atagen2026-09-26 09:41 UTC456
        );
7c26fad34822atagen2026-09-26 09:41 UTC457
        let tick = || UploadProgress {
7c26fad34822atagen2026-09-26 09:41 UTC458
            upload: upload.clone(),
7c26fad34822atagen2026-09-26 09:41 UTC459
            uploaded_bytes: 1,
7c26fad34822atagen2026-09-26 09:41 UTC460
            total_bytes: 2,
7c26fad34822atagen2026-09-26 09:41 UTC461
            complete: false,
7c26fad34822atagen2026-09-26 09:41 UTC462
        };
7c26fad34822atagen2026-09-26 09:41 UTC463
        let mut tracker = UploadTracker {
7c26fad34822atagen2026-09-26 09:41 UTC464
            live: HashSet::new(),
7c26fad34822atagen2026-09-26 09:41 UTC465
            ended: HashSet::new(),
7c26fad34822atagen2026-09-26 09:41 UTC466
        };
7c26fad34822atagen2026-09-26 09:41 UTC467
        assert!(tracker.progress(tick()).is_some());
7c26fad34822atagen2026-09-26 09:41 UTC468
7c26fad34822atagen2026-09-26 09:41 UTC469
        let missed = tracker.resnapshot(HashSet::new());
7c26fad34822atagen2026-09-26 09:41 UTC470
        assert!(matches!(
7c26fad34822atagen2026-09-26 09:41 UTC471
            missed.as_slice(),
7c26fad34822atagen2026-09-26 09:41 UTC472
            [Event::MediaUploadFinished {
7c26fad34822atagen2026-09-26 09:41 UTC473
                outcome: UploadOutcome::Missed,
7c26fad34822atagen2026-09-26 09:41 UTC474
                ..
7c26fad34822atagen2026-09-26 09:41 UTC475
            }]
7c26fad34822atagen2026-09-26 09:41 UTC476
        ));
7c26fad34822atagen2026-09-26 09:41 UTC477
7c26fad34822atagen2026-09-26 09:41 UTC478
        assert!(tracker.progress(tick()).is_none());
7c26fad34822atagen2026-09-26 09:41 UTC479
        let sent = SendQueueUpdate {
7c26fad34822atagen2026-09-26 09:41 UTC480
            room_id: upload.0.clone(),
7c26fad34822atagen2026-09-26 09:41 UTC481
            update: RoomSendQueueUpdate::SentEvent {
7c26fad34822atagen2026-09-26 09:41 UTC482
                transaction_id: upload.1.clone(),
7c26fad34822atagen2026-09-26 09:41 UTC483
                event_id: event_id!("$sent:localhost").to_owned(),
7c26fad34822atagen2026-09-26 09:41 UTC484
            },
7c26fad34822atagen2026-09-26 09:41 UTC485
        };
7c26fad34822atagen2026-09-26 09:41 UTC486
        assert!(tracker.update(sent).is_none());
7c26fad34822atagen2026-09-26 09:41 UTC487
        assert!(tracker.resnapshot(HashSet::from([upload])).is_empty());
7c26fad34822atagen2026-09-26 09:41 UTC488
    }
7c26fad34822atagen2026-09-26 09:41 UTC489
}