atagen

macltok

public
Star0
Watch0
5b21b919d1e6b2bd383e3cfc77ff4f6397d2a488
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/engine/media.rsRust736 lines24.5 KB
1
use std::{
2
    borrow::Cow,
3
    collections::{HashMap, VecDeque},
4
    io::Read as _,
5
    panic::AssertUnwindSafe,
6
    sync::Arc,
7
    time::Duration,
8
};
9
10
use futures_util::{
11
    FutureExt, StreamExt,
12
    future::{Shared, WeakShared},
13
};
14
use matrix_sdk::{
15
    Client, Room, SendOutsideWasm, SyncOutsideWasm,
16
    media::{MediaFormat, MediaRequestParameters, MediaThumbnailSettings},
17
    room::reply::{EnforceThread, Reply as SdkReply},
18
    ruma::{
19
        api::{
20
            Metadata, OutgoingRequest,
21
            auth_scheme::SendAccessToken,
22
            client::{authenticated_media, media},
23
        },
24
        events::room::{
25
            EncryptedFileHash, EncryptedFileHashAlgorithm, EncryptedFileInfo, MediaSource,
26
            message::{AddMentions, ReplyWithinThread},
27
        },
28
    },
29
};
30
use matrix_sdk_crypto::{AttachmentDecryptor, MediaEncryptionInfo};
31
use ruma::MxcUri;
32
use tokio::sync::Mutex;
33
34
use super::executor::EngineBoxFuture;
35
use crate::{
36
    AttachmentEncryption, AttachmentUpload, Error, ErrorKind, Media, MediaFile, MediaId, MediaKind,
37
    MediaLocation, MediaSize, TimelineId,
38
    normalise::{MediaRegistration, MediaScope},
39
    upload::prepare_upload,
40
};
41
42
/// a stalled download gives up after this long without a byte
43
const DOWNLOAD_IDLE: Duration = Duration::from_secs(60);
44
/// the sdk client gives up on any request after thirty seconds, far too soon for a video
45
const DOWNLOAD_TOTAL: Duration = Duration::from_secs(60 * 60);
46
47
type FlightFuture = EngineBoxFuture<'static, Result<Media, Error>>;
48
type Flight = Shared<FlightFuture>;
49
50
/// owns everything needed to turn a media id or an mxc uri into bytes, so the
51
/// handle can answer media queries without a trip through the engine
52
pub(crate) struct MediaService {
53
    client: Client,
54
    registry: Mutex<MediaRegistry>,
55
    flights: Mutex<HashMap<String, WeakShared<FlightFuture>>>,
56
    max_bytes: usize,
57
}
58
59
impl MediaService {
60
    pub(crate) fn new(client: Client, max_bytes: usize, max_sources: usize) -> Self {
61
        Self {
62
            client,
63
            registry: Mutex::new(MediaRegistry::new(max_sources)),
64
            flights: Mutex::new(HashMap::new()),
65
            max_bytes,
66
        }
67
    }
68
69
    pub(crate) async fn register(&self, media: Vec<MediaRegistration>) {
70
        if !media.is_empty() {
71
            self.registry.lock().await.insert_all(media);
72
        }
73
    }
74
75
    pub(crate) async fn release(&self, scope: &MediaScope) {
76
        self.registry.lock().await.release(scope);
77
    }
78
79
    pub(crate) async fn clear(&self) {
80
        self.registry.lock().await.clear();
81
    }
82
83
    pub(crate) async fn timeline_media(
84
        &self,
85
        media_id: &MediaId,
86
        size: MediaSize,
87
    ) -> Result<Media, Error> {
88
        let chosen = choose_source(self.registered(media_id).await?, size)?;
89
        if chosen
90
            .declared_size
91
            .is_some_and(|size| size > self.max_bytes as u64)
92
        {
93
            return Err(too_large("media exceeds the configured byte limit"));
94
        }
95
        self.fetch_or_file(chosen.request, chosen.mimetype).await
96
    }
97
98
    pub(crate) async fn media_location(
99
        &self,
100
        media_id: &MediaId,
101
        size: MediaSize,
102
    ) -> Result<MediaLocation, Error> {
103
        let media = self.registered(media_id).await?;
104
        let chosen = choose_source(media.clone(), size)?;
105
        if is_local(&chosen.request.source) {
106
            return Ok(MediaLocation::Local);
107
        }
108
        if !matches!(chosen.request.format, MediaFormat::Thumbnail(_)) {
109
            return Ok(MediaLocation::File(
110
                media_file(
111
                    &self.client,
112
                    chosen.request,
113
                    chosen.mimetype,
114
                    chosen.declared_size,
115
                )
116
                .await?,
117
            ));
118
        }
119
        let url = media_http_request(&self.client, &chosen.request)
120
            .await?
121
            .uri()
122
            .to_string();
123
        let fallback = MediaRequestParameters {
124
            source: media.full.source,
125
            format: MediaFormat::File,
126
        };
127
        Ok(MediaLocation::ServerThumbnail {
128
            url,
129
            fallback: media_file(
130
                &self.client,
131
                fallback,
132
                media.full.mimetype,
133
                media.full.declared_size,
134
            )
135
            .await?,
136
        })
137
    }
138
139
    async fn registered(&self, media_id: &MediaId) -> Result<MediaRegistration, Error> {
140
        self.registry
141
            .lock()
142
            .await
143
            .get(media_id)
144
            .cloned()
145
            .ok_or_else(|| {
146
                Error::new(
147
                    ErrorKind::MediaUnknown,
148
                    "media is not registered in a retained timeline",
149
                )
150
            })
151
    }
152
153
    pub(crate) async fn mxc_media(&self, uri: &MxcUri, size: MediaSize) -> Result<Media, Error> {
154
        if !uri.is_valid() {
155
            return Err(Error::new(ErrorKind::Invalid, "mxc uri is malformed"));
156
        }
157
        let format = match size {
158
            MediaSize::Full => MediaFormat::File,
159
            MediaSize::Thumbnail { width, height } => thumbnail_format(width, height),
160
        };
161
        self.fetch_or_file(
162
            MediaRequestParameters {
163
                source: MediaSource::Plain(uri.to_owned()),
164
                format,
165
            },
166
            None,
167
        )
168
        .await
169
    }
170
171
    /// plenty of servers won't thumbnail everything, and the file itself is the next best
172
    /// thing. the byte cap still holds either way
173
    async fn fetch_or_file(
174
        &self,
175
        request: MediaRequestParameters,
176
        mimetype: Option<String>,
177
    ) -> Result<Media, Error> {
178
        if !matches!(request.format, MediaFormat::Thumbnail(_)) {
179
            return self.fetch(request, mimetype).await;
180
        }
181
        match self.fetch(request.clone(), mimetype.clone()).await {
182
            Err(error) if error.kind == ErrorKind::MediaUnavailable => {
183
                let file = MediaRequestParameters {
184
                    source: request.source,
185
                    format: MediaFormat::File,
186
                };
187
                self.fetch(file, mimetype).await
188
            }
189
            result => result,
190
        }
191
    }
192
193
    async fn fetch(
194
        &self,
195
        request: MediaRequestParameters,
196
        mimetype: Option<String>,
197
    ) -> Result<Media, Error> {
198
        let key = flight_key(&request);
199
        let flight = {
200
            let mut flights = self.flights.lock().await;
201
            flights.retain(|_, flight| flight.upgrade().is_some());
202
            match flights.get(&key).and_then(WeakShared::upgrade) {
203
                Some(flight) => flight,
204
                None => {
205
                    let prepared = AssertUnwindSafe(fetch(
206
                        self.client.clone(),
207
                        request,
208
                        mimetype,
209
                        self.max_bytes,
210
                    ))
211
                    .catch_unwind()
212
                    .map(|result| {
213
                        result.unwrap_or_else(|_| {
214
                            Err(Error::new(ErrorKind::Other, "media fetch panicked"))
215
                        })
216
                    });
217
                    let boxed: FlightFuture = Box::pin(prepared);
218
                    let flight: Flight = boxed.shared();
219
                    if let Some(weak) = flight.downgrade() {
220
                        flights.insert(key, weak);
221
                    }
222
                    flight
223
                }
224
            }
225
        };
226
        flight.await
227
    }
228
}
229
230
struct ChosenSource {
231
    request: MediaRequestParameters,
232
    mimetype: Option<String>,
233
    declared_size: Option<u64>,
234
}
235
236
fn choose_source(media: MediaRegistration, size: MediaSize) -> Result<ChosenSource, Error> {
237
    let (source, format, mimetype, declared_size) = match size {
238
        MediaSize::Full => (
239
            media.full.source,
240
            MediaFormat::File,
241
            media.full.mimetype,
242
            media.full.declared_size,
243
        ),
244
        MediaSize::Thumbnail { width, height } => match media.thumbnail {
245
            Some(thumbnail) => (
246
                thumbnail.source,
247
                MediaFormat::File,
248
                thumbnail.mimetype,
249
                thumbnail.declared_size,
250
            ),
251
            // the server can only resize what it can read
252
            None if matches!(media.kind, MediaKind::Image | MediaKind::Video)
253
                && matches!(media.full.source, MediaSource::Plain(_)) =>
254
            {
255
                // the server picks the thumbnail's type, so the original's would be a lie
256
                let format = if is_local(&media.full.source) {
257
                    MediaFormat::File
258
                } else {
259
                    thumbnail_format(width, height)
260
                };
261
                (media.full.source, format, None, None)
262
            }
263
            None => {
264
                return Err(Error::new(
265
                    ErrorKind::MediaUnavailable,
266
                    "the requested media size is unavailable",
267
                ));
268
            }
269
        },
270
    };
271
    Ok(ChosenSource {
272
        request: MediaRequestParameters { source, format },
273
        mimetype,
274
        declared_size,
275
    })
276
}
277
278
async fn media_file(
279
    client: &Client,
280
    request: MediaRequestParameters,
281
    mimetype: Option<String>,
282
    declared_size: Option<u64>,
283
) -> Result<MediaFile, Error> {
284
    let url = media_http_request(client, &request)
285
        .await?
286
        .uri()
287
        .to_string();
288
    let encryption = match &request.source {
289
        MediaSource::Plain(_) => None,
290
        MediaSource::Encrypted(file) => {
291
            let (EncryptedFileInfo::V2(info), Some(EncryptedFileHash::Sha256(sha256))) = (
292
                &file.info,
293
                file.hashes.get(&EncryptedFileHashAlgorithm::Sha256),
294
            ) else {
295
                return Err(Error::new(
296
                    ErrorKind::MediaUnavailable,
297
                    "encrypted media is not v2 with a sha256 hash",
298
                ));
299
            };
300
            Some(AttachmentEncryption {
301
                key: info.k.encode(),
302
                iv: info.iv.encode(),
303
                sha256: sha256.encode(),
304
            })
305
        }
306
    };
307
    Ok(MediaFile {
308
        url,
309
        mimetype,
310
        declared_size,
311
        encryption,
312
    })
313
}
314
315
fn thumbnail_format(width: u32, height: u32) -> MediaFormat {
316
    MediaFormat::Thumbnail(MediaThumbnailSettings::new(width.into(), height.into()))
317
}
318
319
fn is_local(source: &MediaSource) -> bool {
320
    let uri = match source {
321
        MediaSource::Plain(uri) => uri,
322
        MediaSource::Encrypted(file) => &file.url,
323
    };
324
    uri.server_name()
325
        .is_ok_and(|server| server.as_str() == "send-queue.localhost")
326
}
327
328
/// plain and encrypted sources share a cache key in the sdk, but must never share a flight
329
fn flight_key(request: &MediaRequestParameters) -> String {
330
    let uri = match &request.source {
331
        MediaSource::Plain(uri) => format!("plain|{uri}"),
332
        MediaSource::Encrypted(file) => format!("encrypted|{}", file.url),
333
    };
334
    match &request.format {
335
        MediaFormat::File => uri.to_owned(),
336
        MediaFormat::Thumbnail(settings) => format!(
337
            "{uri}|{}|{}x{}|{}",
338
            settings.method, settings.width, settings.height, settings.animated
339
        ),
340
    }
341
}
342
343
fn too_large(message: &'static str) -> Error {
344
    Error::new(ErrorKind::MediaTooLarge, message)
345
}
346
347
async fn fetch(
348
    client: Client,
349
    request: MediaRequestParameters,
350
    mimetype: Option<String>,
351
    max_bytes: usize,
352
) -> Result<Media, Error> {
353
    if let Some(cached) = cached_media(&client, &request).await? {
354
        if cached.len() > max_bytes {
355
            if let Ok(store) = client.media_store().lock().await {
356
                let _ = store.remove_media_content(&request).await;
357
            }
358
            return Err(too_large("cached media exceeds the configured byte limit"));
359
        }
360
        // plain and encrypted share a cache key, so a plain fetch of an encrypted file's uri
361
        // leaves ciphertext here. its hash gives it away
362
        if is_ciphertext(&cached, &request.source) {
363
            let bytes = maybe_decrypt(cached, &request, max_bytes)?;
364
            cache(&client, &request, &bytes).await;
365
            return Ok(media(bytes, mimetype));
366
        }
367
        return Ok(media(cached, mimetype));
368
    }
369
    let (bytes, served_mimetype) = download_bounded(&client, &request, max_bytes).await?;
370
    // the sdk caches plaintext under the encrypted key, so we do too or nobody can read anything
371
    let bytes = maybe_decrypt(bytes, &request, max_bytes)?;
372
    cache(&client, &request, &bytes).await;
373
    Ok(media(bytes, mimetype.or(served_mimetype)))
374
}
375
376
async fn cache(client: &Client, request: &MediaRequestParameters, bytes: &[u8]) {
377
    if let Ok(store) = client.media_store().lock().await {
378
        let _ = store
379
            .add_media_content(
380
                request,
381
                bytes.to_vec(),
382
                matrix_sdk::media::store::IgnoreMediaRetentionPolicy::No,
383
            )
384
            .await;
385
    }
386
}
387
388
fn is_ciphertext(bytes: &[u8], source: &MediaSource) -> bool {
389
    use sha2::{Digest, Sha256};
390
    let MediaSource::Encrypted(file) = source else {
391
        return false;
392
    };
393
    file.hashes
394
        .get(&ruma::events::room::EncryptedFileHashAlgorithm::Sha256)
395
        .is_some_and(|hash| hash.as_bytes() == Sha256::digest(bytes).as_slice())
396
}
397
398
fn media(bytes: Vec<u8>, mimetype: Option<String>) -> Media {
399
    let mimetype = mimetype
400
        .or_else(|| sniff_image(&bytes).map(str::to_owned))
401
        .unwrap_or_else(|| "application/octet-stream".to_owned());
402
    Media {
403
        bytes: Arc::from(bytes),
404
        mimetype,
405
    }
406
}
407
408
/// the cache forgets content types, and avatars never declare one. images are the common case
409
fn sniff_image(bytes: &[u8]) -> Option<&'static str> {
410
    match bytes {
411
        [0x89, b'P', b'N', b'G', ..] => Some("image/png"),
412
        [0xff, 0xd8, 0xff, ..] => Some("image/jpeg"),
413
        [b'G', b'I', b'F', b'8', ..] => Some("image/gif"),
414
        [
415
            b'R',
416
            b'I',
417
            b'F',
418
            b'F',
419
            _,
420
            _,
421
            _,
422
            _,
423
            b'W',
424
            b'E',
425
            b'B',
426
            b'P',
427
            ..,
428
        ] => Some("image/webp"),
429
        _ => None,
430
    }
431
}
432
433
async fn cached_media(
434
    client: &Client,
435
    request: &MediaRequestParameters,
436
) -> Result<Option<Vec<u8>>, Error> {
437
    fn cache_failed(
438
        source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
439
    ) -> Error {
440
        Error::with_source(ErrorKind::Store, "reading media cache failed", source)
441
    }
442
    client
443
        .media_store()
444
        .lock()
445
        .await
446
        .map_err(cache_failed)?
447
        .get_media_content(request)
448
        .await
449
        .map_err(cache_failed)
450
}
451
452
fn maybe_decrypt(
453
    bytes: Vec<u8>,
454
    request: &MediaRequestParameters,
455
    max_bytes: usize,
456
) -> Result<Vec<u8>, Error> {
457
    let MediaSource::Encrypted(file) = &request.source else {
458
        return Ok(bytes);
459
    };
460
    fn decrypt_failed(
461
        source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
462
    ) -> Error {
463
        Error::with_source(
464
            ErrorKind::MediaUnavailable,
465
            "media decryption failed",
466
            source,
467
        )
468
    }
469
    let info: MediaEncryptionInfo = (**file).clone().into();
470
    let mut cursor = std::io::Cursor::new(bytes);
471
    let mut decryptor = AttachmentDecryptor::new(&mut cursor, info).map_err(decrypt_failed)?;
472
    let mut decrypted = Vec::new();
473
    let mut chunk = [0_u8; 8192];
474
    loop {
475
        let read = decryptor.read(&mut chunk).map_err(decrypt_failed)?;
476
        if read == 0 {
477
            return Ok(decrypted);
478
        }
479
        if read > max_bytes.saturating_sub(decrypted.len()) {
480
            return Err(too_large(
481
                "decrypted media exceeds the configured byte limit",
482
            ));
483
        }
484
        decrypted.extend_from_slice(&chunk[..read]);
485
    }
486
}
487
488
/// the sdk's own download has no size cap, so we do it by hand
489
async fn download_bounded(
490
    client: &Client,
491
    request: &MediaRequestParameters,
492
    max_bytes: usize,
493
) -> Result<(Vec<u8>, Option<String>), Error> {
494
    if is_local(&request.source) {
495
        return Err(Error::new(
496
            ErrorKind::MediaUnavailable,
497
            "local media is not in the media cache",
498
        ));
499
    }
500
    let network_failed =
501
        |source| Error::with_source(ErrorKind::Network, "media download failed", source);
502
    let mut refreshed = false;
503
    let response = loop {
504
        let http_request = media_http_request(client, request).await?;
505
        let (parts, _) = http_request.into_parts();
506
        let mut builder = client
507
            .http_client()
508
            .get(parts.uri.to_string())
509
            .timeout(DOWNLOAD_TOTAL);
510
        for (name, value) in &parts.headers {
511
            builder = builder.header(name.as_str(), value.as_bytes());
512
        }
513
        let response = builder.send().await.map_err(network_failed)?;
514
        if response.status() != matrix_sdk::reqwest::StatusCode::UNAUTHORIZED {
515
            break response;
516
        }
517
        if refreshed
518
            || client
519
                .session_tokens()
520
                .is_none_or(|tokens| tokens.refresh_token.is_none())
521
        {
522
            return Err(Error::new(
523
                ErrorKind::Unauthenticated,
524
                "media download was not authorized",
525
            ));
526
        }
527
        client.refresh_access_token().await.map_err(|source| {
528
            Error::from_refresh_token("refreshing media access token failed", source)
529
        })?;
530
        refreshed = true;
531
    };
532
    let status = response.status();
533
    if !status.is_success() {
534
        return Err(Error::new(
535
            ErrorKind::MediaUnavailable,
536
            format!("media download failed with status {status}"),
537
        ));
538
    }
539
    if response
540
        .content_length()
541
        .is_some_and(|length| length > max_bytes as u64)
542
    {
543
        return Err(too_large("media exceeds the configured byte limit"));
544
    }
545
    let mimetype = response
546
        .headers()
547
        .get(http::header::CONTENT_TYPE)
548
        .and_then(|value| value.to_str().ok())
549
        .map(str::to_owned);
550
    let mut stream = response.bytes_stream();
551
    let mut bytes = Vec::new();
552
    loop {
553
        let chunk = matrix_sdk::timeout::timeout(stream.next(), DOWNLOAD_IDLE)
554
            .await
555
            .map_err(|_| Error::new(ErrorKind::Network, "media download stalled"))?;
556
        let Some(chunk) = chunk else { break };
557
        let chunk = chunk.map_err(network_failed)?;
558
        if chunk.len() > max_bytes.saturating_sub(bytes.len()) {
559
            return Err(too_large(
560
                "downloaded media exceeds the configured byte limit",
561
            ));
562
        }
563
        bytes.extend_from_slice(&chunk);
564
    }
565
    Ok((bytes, mimetype))
566
}
567
568
async fn media_http_request(
569
    client: &Client,
570
    request: &MediaRequestParameters,
571
) -> Result<http::Request<Vec<u8>>, Error> {
572
    let versions = client.supported_versions().await.map_err(|source| {
573
        Error::with_source(
574
            ErrorKind::Network,
575
            "reading supported server versions failed",
576
            source,
577
        )
578
    })?;
579
    let authenticated =
580
        authenticated_media::get_content::v1::Request::PATH_BUILDER.is_supported(&versions);
581
    let base = client.homeserver().to_string();
582
    let token = client.access_token();
583
    let invalid_uri =
584
        |source| Error::with_source(ErrorKind::Invalid, "media URI is invalid", source);
585
    let (uri, thumbnail) = match (&request.source, &request.format) {
586
        (MediaSource::Encrypted(file), _) => (&file.url, None),
587
        (MediaSource::Plain(uri), MediaFormat::File) => (uri, None),
588
        (MediaSource::Plain(uri), MediaFormat::Thumbnail(settings)) => (uri, Some(settings)),
589
    };
590
    // each endpoint has its own auth input type, so no generic helper can take them all
591
    macro_rules! into_http {
592
        ($endpoint:expr, $token:expr) => {
593
            $endpoint
594
                .try_into_http_request::<Vec<u8>>(&base, $token, Cow::Borrowed(&versions))
595
                .map_err(|source| {
596
                    Error::with_source(ErrorKind::Other, "media request is invalid", source)
597
                })?
598
        };
599
    }
600
    let authed = SendAccessToken::IfRequired(token.as_deref().unwrap_or(""));
601
    #[allow(deprecated)]
602
    let mut http_request = match (thumbnail, authenticated) {
603
        (None, true) => into_http!(
604
            authenticated_media::get_content::v1::Request::from_uri(uri).map_err(invalid_uri)?,
605
            authed
606
        ),
607
        (None, false) => into_http!(
608
            media::get_content::v3::Request::from_url(uri).map_err(invalid_uri)?,
609
            SendAccessToken::None
610
        ),
611
        (Some(settings), true) => {
612
            let mut endpoint = authenticated_media::get_content_thumbnail::v1::Request::from_uri(
613
                uri,
614
                settings.width,
615
                settings.height,
616
            )
617
            .map_err(invalid_uri)?;
618
            endpoint.method = Some(settings.method.clone());
619
            endpoint.animated = Some(settings.animated);
620
            into_http!(endpoint, authed)
621
        }
622
        (Some(settings), false) => {
623
            let mut endpoint = media::get_content_thumbnail::v3::Request::from_url(
624
                uri,
625
                settings.width,
626
                settings.height,
627
            )
628
            .map_err(invalid_uri)?;
629
            endpoint.method = Some(settings.method.clone());
630
            endpoint.animated = Some(settings.animated);
631
            into_http!(endpoint, SendAccessToken::None)
632
        }
633
    };
634
    // legacy endpoints don't ask for a token but plenty of servers want one anyway
635
    if let Some(token) = token.as_deref() {
636
        let value = format!("Bearer {token}").parse().map_err(|_| {
637
            Error::new(ErrorKind::Unauthenticated, "stored access token is invalid")
638
        })?;
639
        http_request
640
            .headers_mut()
641
            .insert(http::header::AUTHORIZATION, value);
642
    }
643
    Ok(http_request)
644
}
645
646
pub(crate) async fn queue_upload(
647
    room: Room,
648
    upload: AttachmentUpload,
649
    max_bytes: usize,
650
) -> Result<(), Error> {
651
    let (upload, mime, mut config) = prepare_upload(upload, max_bytes)?;
652
    if let TimelineId::Thread { root_event_id, .. } = &upload.timeline_id {
653
        config.reply = Some(SdkReply {
654
            event_id: root_event_id.clone(),
655
            enforce_thread: EnforceThread::Threaded(ReplyWithinThread::No),
656
            add_mentions: AddMentions::No,
657
        });
658
    }
659
    room.send_queue()
660
        .send_attachment(upload.filename, mime, upload.bytes, config)
661
        .await
662
        .map(drop)
663
        .map_err(|source| {
664
            use matrix_sdk::send_queue::RoomSendQueueError;
665
            let kind = match &source {
666
                RoomSendQueueError::RoomNotJoined | RoomSendQueueError::RoomDisappeared => {
667
                    ErrorKind::RoomUnknown
668
                }
669
                RoomSendQueueError::StorageError(_) => ErrorKind::Store,
670
                _ => ErrorKind::MediaUnavailable,
671
            };
672
            Error::with_source(kind, "media upload could not be queued", source)
673
        })
674
}
675
676
/// least recently seen goes first. stale order slots are skipped by stamp rather than hunted down
677
struct MediaRegistry {
678
    entries: HashMap<MediaId, (MediaRegistration, u64)>,
679
    order: VecDeque<(MediaId, u64)>,
680
    next_stamp: u64,
681
    limit: usize,
682
}
683
684
impl MediaRegistry {
685
    fn new(limit: usize) -> Self {
686
        Self {
687
            entries: HashMap::new(),
688
            order: VecDeque::new(),
689
            next_stamp: 0,
690
            limit,
691
        }
692
    }
693
694
    fn get(&self, id: &MediaId) -> Option<&MediaRegistration> {
695
        self.entries.get(id).map(|(media, _)| media)
696
    }
697
698
    fn insert_all(&mut self, media: Vec<MediaRegistration>) {
699
        for media in media {
700
            let stamp = self.next_stamp;
701
            self.next_stamp += 1;
702
            self.order.push_back((media.id.clone(), stamp));
703
            self.entries.insert(media.id.clone(), (media, stamp));
704
        }
705
        while self.entries.len() > self.limit {
706
            let Some((id, stamp)) = self.order.pop_front() else {
707
                break;
708
            };
709
            if self.is_current(&id, stamp) {
710
                self.entries.remove(&id);
711
            }
712
        }
713
        if self.order.len() > self.limit.saturating_mul(4) {
714
            let entries = &self.entries;
715
            self.order
716
                .retain(|(id, stamp)| entries.get(id).is_some_and(|(_, current)| current == stamp));
717
        }
718
    }
719
720
    fn is_current(&self, id: &MediaId, stamp: u64) -> bool {
721
        self.entries
722
            .get(id)
723
            .is_some_and(|(_, current)| *current == stamp)
724
    }
725
726
    fn release(&mut self, scope: &MediaScope) {
727
        self.entries.retain(|id, _| !scope.owns(id));
728
        let entries = &self.entries;
729
        self.order.retain(|(id, _)| entries.contains_key(id));
730
    }
731
732
    fn clear(&mut self) {
733
        self.entries.clear();
734
        self.order.clear();
735
    }
736
}