matrix_sdk_base/event_cache/store/media/media_service.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
// Copyright 2025 Kévin Commaille
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{fmt, sync::Arc};
use async_trait::async_trait;
use matrix_sdk_common::{
executor::{spawn, JoinHandle},
locks::Mutex,
AsyncTraitDeps, SendOutsideWasm, SyncOutsideWasm,
};
use ruma::{time::SystemTime, MxcUri};
use tokio::sync::Mutex as AsyncMutex;
use tracing::error;
use super::MediaRetentionPolicy;
use crate::{event_cache::store::EventCacheStoreError, media::MediaRequestParameters};
/// API for implementors of [`EventCacheStore`] to manage their media through
/// their implementation of [`EventCacheStoreMedia`].
///
/// [`EventCacheStore`]: crate::event_cache::store::EventCacheStore
#[derive(Debug)]
pub struct MediaService<Time: TimeProvider = DefaultTimeProvider> {
inner: Arc<MediaServiceInner<Time>>,
}
#[derive(Debug)]
struct MediaServiceInner<Time: TimeProvider = DefaultTimeProvider> {
/// The time provider.
time_provider: Time,
/// The current [`MediaRetentionPolicy`].
policy: Mutex<MediaRetentionPolicy>,
/// A mutex to ensure a single cleanup is running at a time.
cleanup_guard: AsyncMutex<()>,
/// The time of the last media cache cleanup.
last_media_cleanup_time: Mutex<Option<SystemTime>>,
/// The [`JoinHandle`] for an automatic media cleanup task.
///
/// Used to ensure that only one automatic cleanup is running at a time, and
/// to stop the cleanup when the [`MediaServiceInner`] is dropped.
automatic_media_cleanup_join_handle: Mutex<Option<JoinHandle<()>>>,
}
impl MediaService {
/// Construct a new default `MediaService`.
///
/// [`MediaService::restore()`] should be called after constructing the
/// `MediaService` to restore its previous state.
pub fn new() -> Self {
Self::default()
}
}
impl Default for MediaService {
fn default() -> Self {
Self::with_time_provider(DefaultTimeProvider)
}
}
impl<Time> MediaService<Time>
where
Time: TimeProvider + 'static,
{
/// Construct a new `MediaService` with the given `TimeProvider` and an
/// empty `MediaRetentionPolicy`.
fn with_time_provider(time_provider: Time) -> Self {
let inner = MediaServiceInner {
time_provider,
policy: Mutex::new(MediaRetentionPolicy::empty()),
cleanup_guard: AsyncMutex::new(()),
last_media_cleanup_time: Mutex::new(None),
automatic_media_cleanup_join_handle: Mutex::new(None),
};
Self { inner: Arc::new(inner) }
}
/// Restore the previous state of the [`MediaRetentionPolicy`] from data
/// that was persisted in the store.
///
/// This should be called immediately after constructing the `MediaService`.
///
/// # Arguments
///
/// * `policy` - The `MediaRetentionPolicy` that was persisted in the store.
pub fn restore(
&self,
policy: Option<MediaRetentionPolicy>,
last_media_cleanup_time: Option<SystemTime>,
) {
if let Some(policy) = policy {
*self.inner.policy.lock() = policy;
}
if let Some(time) = last_media_cleanup_time {
*self.inner.last_media_cleanup_time.lock() = Some(time);
}
}
/// Get the current time from the inner [`TimeProvider`].
fn now(&self) -> SystemTime {
self.inner.time_provider.now()
}
/// Set the `MediaRetentionPolicy` of this service.
///
/// # Arguments
///
/// * `store` - The `EventCacheStoreMedia`.
///
/// * `policy` - The `MediaRetentionPolicy` to use.
pub async fn set_media_retention_policy<Store: EventCacheStoreMedia + 'static>(
&self,
store: &Store,
policy: MediaRetentionPolicy,
) -> Result<(), Store::Error> {
store.set_media_retention_policy_inner(policy).await?;
*self.inner.policy.lock() = policy;
self.maybe_spawn_automatic_media_cache_cleanup(store, self.now());
Ok(())
}
/// Get the `MediaRetentionPolicy` of this service.
pub fn media_retention_policy(&self) -> MediaRetentionPolicy {
*self.inner.policy.lock()
}
/// Add a media file's content in the media store.
///
/// # Arguments
///
/// * `store` - The `EventCacheStoreMedia`.
///
/// * `request` - The `MediaRequestParameters` of the file.
///
/// * `content` - The content of the file.
///
/// * `ignore_policy` - Whether the current `MediaRetentionPolicy` should be
/// ignored.
pub async fn add_media_content<Store: EventCacheStoreMedia + 'static>(
&self,
store: &Store,
request: &MediaRequestParameters,
content: Vec<u8>,
ignore_policy: IgnoreMediaRetentionPolicy,
) -> Result<(), Store::Error> {
let policy = self.media_retention_policy();
if ignore_policy == IgnoreMediaRetentionPolicy::No
&& policy.exceeds_max_file_size(content.len() as u64)
{
// We do not cache the content.
return Ok(());
}
let current_time = self.now();
store
.add_media_content_inner(request, content, current_time, policy, ignore_policy)
.await?;
self.maybe_spawn_automatic_media_cache_cleanup(store, current_time);
Ok(())
}
/// Set whether the current [`MediaRetentionPolicy`] should be ignored for
/// the media.
///
/// The change will be taken into account in the next cleanup.
///
/// # Arguments
///
/// * `store` - The `EventCacheStoreMedia`.
///
/// * `request` - The `MediaRequestParameters` of the file.
///
/// * `ignore_policy` - Whether the current `MediaRetentionPolicy` should be
/// ignored.
pub async fn set_ignore_media_retention_policy<Store: EventCacheStoreMedia>(
&self,
store: &Store,
request: &MediaRequestParameters,
ignore_policy: IgnoreMediaRetentionPolicy,
) -> Result<(), Store::Error> {
store.set_ignore_media_retention_policy_inner(request, ignore_policy).await
}
/// Get a media file's content out of the media store.
///
/// # Arguments
///
/// * `store` - The `EventCacheStoreMedia`.
///
/// * `request` - The `MediaRequestParameters` of the file.
pub async fn get_media_content<Store: EventCacheStoreMedia + 'static>(
&self,
store: &Store,
request: &MediaRequestParameters,
) -> Result<Option<Vec<u8>>, Store::Error> {
let current_time = self.now();
let content = store.get_media_content_inner(request, current_time).await?;
self.maybe_spawn_automatic_media_cache_cleanup(store, current_time);
Ok(content)
}
/// Get a media file's content associated to an `MxcUri` from the
/// media store.
///
/// # Arguments
///
/// * `store` - The `EventCacheStoreMedia`.
///
/// * `uri` - The `MxcUri` of the media file.
pub async fn get_media_content_for_uri<Store: EventCacheStoreMedia + 'static>(
&self,
store: &Store,
uri: &MxcUri,
) -> Result<Option<Vec<u8>>, Store::Error> {
let current_time = self.now();
let content = store.get_media_content_for_uri_inner(uri, current_time).await?;
self.maybe_spawn_automatic_media_cache_cleanup(store, current_time);
Ok(content)
}
/// Clean up the media cache with the current `MediaRetentionPolicy`.
///
/// If there is already an ongoing cleanup, this is a noop.
///
/// # Arguments
///
/// * `store` - The `EventCacheStoreMedia`.
pub async fn clean_up_media_cache<Store: EventCacheStoreMedia>(
&self,
store: &Store,
) -> Result<(), Store::Error> {
self.clean_up_media_cache_inner(store, self.now()).await
}
async fn clean_up_media_cache_inner<Store: EventCacheStoreMedia>(
&self,
store: &Store,
current_time: SystemTime,
) -> Result<(), Store::Error> {
let Ok(_guard) = self.inner.cleanup_guard.try_lock() else {
// There is another ongoing cleanup.
return Ok(());
};
let policy = self.media_retention_policy();
if !policy.has_limitations() {
// No need to call the backend.
return Ok(());
}
store.clean_up_media_cache_inner(policy, current_time).await?;
*self.inner.last_media_cleanup_time.lock() = Some(current_time);
Ok(())
}
/// Spawn an automatic media cache cleanup, according to the media retention
/// policy.
///
/// A cleanup will be spawned if:
/// * The media retention policy's `cleanup_frequency` is set and enough
/// time has passed since the last cleanup.
/// * No other cleanup is running,
fn maybe_spawn_automatic_media_cache_cleanup<Store: EventCacheStoreMedia + 'static>(
&self,
store: &Store,
current_time: SystemTime,
) {
let mut join_handle = self.inner.automatic_media_cleanup_join_handle.lock();
if join_handle.as_ref().is_some_and(|join_handle| !join_handle.is_finished()) {
// There is an ongoing automatic media cache cleanup.
return;
}
let policy = self.media_retention_policy();
if policy.cleanup_frequency.is_none() || !policy.has_limitations() {
// Automatic cleanups are disabled or have no effect.
return;
}
let last_media_cleanup_time = *self.inner.last_media_cleanup_time.lock();
if last_media_cleanup_time.is_some_and(|last_cleanup_time| {
!policy.should_clean_up(current_time, last_cleanup_time)
}) {
// It is not time to clean up.
return;
}
let this = self.clone();
let store = store.clone();
let handle = spawn(async move {
if let Err(error) = this.clean_up_media_cache_inner(&store, current_time).await {
error!("Failed to run automatic media cache cleanup: {error}");
}
});
*join_handle = Some(handle);
}
}
impl<Time> Clone for MediaService<Time>
where
Time: TimeProvider,
{
fn clone(&self) -> Self {
Self { inner: self.inner.clone() }
}
}
impl<Time> Drop for MediaServiceInner<Time>
where
Time: TimeProvider,
{
fn drop(&mut self) {
if let Some(join_handle) = self.automatic_media_cleanup_join_handle.lock().take() {
join_handle.abort();
}
}
}
/// An abstract trait that can be used to implement different store backends
/// for the media cache of the SDK.
///
/// The main purposes of this trait are to be able to centralize where we handle
/// [`MediaRetentionPolicy`] by wrapping this in a [`MediaService`], and to
/// simplify the implementation of tests by being able to have complete control
/// over the `SystemTime`s provided to the store.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait EventCacheStoreMedia: AsyncTraitDeps + Clone {
/// The error type used by this media cache store.
type Error: fmt::Debug + fmt::Display + Into<EventCacheStoreError>;
/// The persisted media retention policy in the media cache.
async fn media_retention_policy_inner(
&self,
) -> Result<Option<MediaRetentionPolicy>, Self::Error>;
/// Persist the media retention policy in the media cache.
///
/// # Arguments
///
/// * `policy` - The `MediaRetentionPolicy` to persist.
async fn set_media_retention_policy_inner(
&self,
policy: MediaRetentionPolicy,
) -> Result<(), Self::Error>;
/// Add a media file's content in the media cache.
///
/// # Arguments
///
/// * `request` - The `MediaRequestParameters` of the file.
///
/// * `content` - The content of the file.
///
/// * `current_time` - The current time, to set the last access time of the
/// media.
///
/// * `policy` - The media retention policy, to check whether the media is
/// too big to be cached.
///
/// * `ignore_policy` - Whether the `MediaRetentionPolicy` should be ignored
/// for this media. This setting should be persisted alongside the media
/// and taken into account whenever the policy is used.
async fn add_media_content_inner(
&self,
request: &MediaRequestParameters,
content: Vec<u8>,
current_time: SystemTime,
policy: MediaRetentionPolicy,
ignore_policy: IgnoreMediaRetentionPolicy,
) -> Result<(), Self::Error>;
/// Set whether the current [`MediaRetentionPolicy`] should be ignored for
/// the media.
///
/// If the media of the given request is not found, this should be a noop.
///
/// The change will be taken into account in the next cleanup.
///
/// # Arguments
///
/// * `request` - The `MediaRequestParameters` of the file.
///
/// * `ignore_policy` - Whether the current `MediaRetentionPolicy` should be
/// ignored.
async fn set_ignore_media_retention_policy_inner(
&self,
request: &MediaRequestParameters,
ignore_policy: IgnoreMediaRetentionPolicy,
) -> Result<(), Self::Error>;
/// Get a media file's content out of the media cache.
///
/// # Arguments
///
/// * `request` - The `MediaRequestParameters` of the file.
///
/// * `current_time` - The current time, to update the last access time of
/// the media.
async fn get_media_content_inner(
&self,
request: &MediaRequestParameters,
current_time: SystemTime,
) -> Result<Option<Vec<u8>>, Self::Error>;
/// Get a media file's content associated to an `MxcUri` from the
/// media store.
///
/// # Arguments
///
/// * `uri` - The `MxcUri` of the media file.
///
/// * `current_time` - The current time, to update the last access time of
/// the media.
async fn get_media_content_for_uri_inner(
&self,
uri: &MxcUri,
current_time: SystemTime,
) -> Result<Option<Vec<u8>>, Self::Error>;
/// Clean up the media cache with the given policy.
///
/// For the integration tests, it is expected that content that does not
/// pass the last access expiry and max file size criteria will be
/// removed first. After that, the remaining cache size should be
/// computed to compare against the max cache size criteria.
///
/// # Arguments
///
/// * `policy` - The media retention policy to use for the cleanup. The
/// `cleanup_frequency` will be ignored.
///
/// * `current_time` - The current time, to be used to check for expired
/// content and to be stored as the time of the last media cache cleanup.
async fn clean_up_media_cache_inner(
&self,
policy: MediaRetentionPolicy,
current_time: SystemTime,
) -> Result<(), Self::Error>;
/// The time of the last media cache cleanup.
async fn last_media_cleanup_time_inner(&self) -> Result<Option<SystemTime>, Self::Error>;
}
/// Whether the [`MediaRetentionPolicy`] should be ignored for the current
/// content.
///
/// Some media cache actions are noops when the media content that is processed
/// is filtered out by the policy. This can break some features of the SDK, like
/// the send queue, that expects to be able to persist all media files in the
/// store to restore them when the client is restored.
///
/// This can be converted to a boolean with
/// [`IgnoreMediaRetentionPolicy::is_yes()`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IgnoreMediaRetentionPolicy {
/// The media retention policy will be ignored and the current action will
/// not be a noop.
///
/// Any media content in this state must NOT be used when applying a
/// `MediaRetentionPolicy`. This applies to ANY criteria, like the maximum
/// file size, the maximum cache size or the last access expiry.
///
/// This state is supposed to be transient, and to only be used internally
/// by the SDK.
Yes,
/// The media retention policy will be respected and the current action
/// might be a noop.
No,
}
impl IgnoreMediaRetentionPolicy {
/// Whether this is an [`IgnoreMediaRetentionPolicy::Yes`] variant.
pub fn is_yes(self) -> bool {
matches!(self, Self::Yes)
}
}
/// An abstract trait to provide the current `SystemTime` for the
/// [`MediaService`].
pub trait TimeProvider: SendOutsideWasm + SyncOutsideWasm {
/// The current time.
fn now(&self) -> SystemTime;
}
/// The default time provider, that calls `ruma::time::SystemTime::now()`.
#[derive(Debug)]
pub struct DefaultTimeProvider;
impl TimeProvider for DefaultTimeProvider {
fn now(&self) -> SystemTime {
SystemTime::now()
}
}
#[cfg(test)]
mod tests {
use std::{
fmt,
sync::{Arc, MutexGuard},
};
use async_trait::async_trait;
use matrix_sdk_common::locks::Mutex;
use matrix_sdk_test::async_test;
use ruma::{
events::room::MediaSource,
mxc_uri,
time::{Duration, SystemTime},
MxcUri, OwnedMxcUri,
};
use super::{EventCacheStoreMedia, IgnoreMediaRetentionPolicy, MediaService, TimeProvider};
use crate::{
event_cache::store::{media::MediaRetentionPolicy, EventCacheStoreError},
media::{MediaFormat, MediaRequestParameters, UniqueKey},
};
#[derive(Debug, Default, Clone)]
struct MockEventCacheStoreMedia {
inner: Arc<Mutex<MockEventCacheStoreMediaInner>>,
}
impl MockEventCacheStoreMedia {
/// Whether the store was accessed.
fn accessed(&self) -> bool {
self.inner.lock().accessed
}
/// Reset the `accessed` boolean.
fn reset_accessed(&self) {
self.inner.lock().accessed = false;
}
/// Access the inner store.
///
/// Should be called for every access to the inner store as it also sets
/// the `accessed` boolean.
fn inner(&self) -> MutexGuard<'_, MockEventCacheStoreMediaInner> {
let mut inner = self.inner.lock();
inner.accessed = true;
inner
}
}
#[derive(Debug, Default)]
struct MockEventCacheStoreMediaInner {
/// Whether this store was accessed.
///
/// Must be set to `true` for any operation that unlocks the store.
accessed: bool,
/// The persisted media retention policy.
media_retention_policy: Option<MediaRetentionPolicy>,
/// The list of media content.
media_list: Vec<MediaContent>,
/// The time of the last cleanup.
cleanup_time: Option<SystemTime>,
}
#[derive(Debug, Clone)]
struct MediaContent {
/// The unique key for the media content.
key: String,
/// The original URI of the media content.
uri: OwnedMxcUri,
/// The media content.
content: Vec<u8>,
/// Whether the `MediaRetentionPolicy` should be ignored for this media
/// content;
ignore_policy: bool,
/// The time of the last access of the media content.
last_access: SystemTime,
}
#[derive(Debug)]
struct MockEventCacheStoreMediaError;
impl fmt::Display for MockEventCacheStoreMediaError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "MockEventCacheStoreMediaError")
}
}
impl std::error::Error for MockEventCacheStoreMediaError {}
impl From<MockEventCacheStoreMediaError> for EventCacheStoreError {
fn from(value: MockEventCacheStoreMediaError) -> Self {
Self::backend(value)
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EventCacheStoreMedia for MockEventCacheStoreMedia {
type Error = MockEventCacheStoreMediaError;
async fn media_retention_policy_inner(
&self,
) -> Result<Option<MediaRetentionPolicy>, Self::Error> {
Ok(self.inner().media_retention_policy)
}
async fn set_media_retention_policy_inner(
&self,
policy: MediaRetentionPolicy,
) -> Result<(), Self::Error> {
self.inner().media_retention_policy = Some(policy);
Ok(())
}
async fn add_media_content_inner(
&self,
request: &MediaRequestParameters,
content: Vec<u8>,
current_time: SystemTime,
policy: MediaRetentionPolicy,
ignore_policy: IgnoreMediaRetentionPolicy,
) -> Result<(), Self::Error> {
let ignore_policy = ignore_policy.is_yes();
if !ignore_policy && policy.exceeds_max_file_size(content.len() as u64) {
return Ok(());
}
let mut inner = self.inner();
let key = request.unique_key();
if let Some(pos) = inner.media_list.iter().position(|content| content.key == key) {
let media_content = &mut inner.media_list[pos];
media_content.content = content;
media_content.last_access = current_time;
media_content.ignore_policy = ignore_policy;
} else {
inner.media_list.push(MediaContent {
key,
uri: request.uri().to_owned(),
content,
ignore_policy,
last_access: current_time,
});
}
Ok(())
}
async fn set_ignore_media_retention_policy_inner(
&self,
request: &MediaRequestParameters,
ignore_policy: IgnoreMediaRetentionPolicy,
) -> Result<(), Self::Error> {
let key = request.unique_key();
let mut inner = self.inner();
if let Some(pos) = inner.media_list.iter().position(|content| content.key == key) {
inner.media_list[pos].ignore_policy = ignore_policy.is_yes();
}
Ok(())
}
async fn get_media_content_inner(
&self,
request: &MediaRequestParameters,
current_time: SystemTime,
) -> Result<Option<Vec<u8>>, Self::Error> {
let key = request.unique_key();
let mut inner = self.inner();
let Some(media_content) =
inner.media_list.iter_mut().find(|content| content.key == key)
else {
return Ok(None);
};
media_content.last_access = current_time;
Ok(Some(media_content.content.clone()))
}
async fn get_media_content_for_uri_inner(
&self,
uri: &MxcUri,
current_time: SystemTime,
) -> Result<Option<Vec<u8>>, Self::Error> {
let mut inner = self.inner();
let Some(media_content) =
inner.media_list.iter_mut().find(|content| content.uri == uri)
else {
return Ok(None);
};
media_content.last_access = current_time;
Ok(Some(media_content.content.clone()))
}
async fn clean_up_media_cache_inner(
&self,
_policy: MediaRetentionPolicy,
current_time: SystemTime,
) -> Result<(), Self::Error> {
// This is mostly a noop. We don't care about this test implementation, only
// whether this method was called with the right time.
self.inner().cleanup_time = Some(current_time);
Ok(())
}
async fn last_media_cleanup_time_inner(&self) -> Result<Option<SystemTime>, Self::Error> {
Ok(self.inner().cleanup_time)
}
}
#[derive(Debug)]
struct MockTimeProvider {
now: Mutex<SystemTime>,
}
impl MockTimeProvider {
/// Construct a `MockTimeProvider` with the given current time.
fn new(now: SystemTime) -> Self {
Self { now: Mutex::new(now) }
}
/// Set the current time.
fn set_now(&self, now: SystemTime) {
*self.now.lock() = now;
}
}
impl TimeProvider for MockTimeProvider {
fn now(&self) -> SystemTime {
*self.now.lock()
}
}
#[async_test]
async fn test_media_service_empty_policy() {
let content = b"some text content";
let uri = mxc_uri!("mxc://server.local/AbcDe1234");
let request = MediaRequestParameters {
source: MediaSource::Plain(uri.to_owned()),
format: MediaFormat::File,
};
let now = SystemTime::UNIX_EPOCH;
let store = MockEventCacheStoreMedia::default();
let service = MediaService::with_time_provider(MockTimeProvider::new(now));
// By default an empty policy is used.
assert!(!service.media_retention_policy().has_limitations());
service.restore(None, None);
assert!(!service.media_retention_policy().has_limitations());
assert!(!store.accessed());
// Add media.
service
.add_media_content(&store, &request, content.to_vec(), IgnoreMediaRetentionPolicy::No)
.await
.unwrap();
assert!(store.accessed());
let media_content = store.inner().media_list[0].clone();
assert_eq!(media_content.uri, uri);
assert_eq!(media_content.content, content);
assert!(!media_content.ignore_policy);
assert_eq!(media_content.last_access, now);
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
store.reset_accessed();
// Get media from request.
let loaded_content = service.get_media_content(&store, &request).await.unwrap();
assert!(store.accessed());
assert_eq!(loaded_content.as_deref(), Some(content.as_slice()));
// The last access time was updated.
let media = store.inner().media_list[0].clone();
assert_eq!(media.last_access, now);
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
store.reset_accessed();
// Get media from URI.
let loaded_content = service.get_media_content_for_uri(&store, uri).await.unwrap();
assert!(store.accessed());
assert_eq!(loaded_content.as_deref(), Some(content.as_slice()));
// The last access time was updated.
let media = store.inner().media_list[0].clone();
assert_eq!(media.last_access, now);
// Update ignore_policy.
service
.set_ignore_media_retention_policy(&store, &request, IgnoreMediaRetentionPolicy::Yes)
.await
.unwrap();
assert!(store.accessed());
let media_content = store.inner().media_list[0].clone();
assert!(media_content.ignore_policy);
// Try a cleanup. With the empty policy the store should not be accessed.
assert_eq!(store.last_media_cleanup_time_inner().await.unwrap(), None);
store.reset_accessed();
service.clean_up_media_cache(&store).await.unwrap();
assert!(!store.accessed());
assert_eq!(store.last_media_cleanup_time_inner().await.unwrap(), None);
}
#[async_test]
async fn test_media_service_non_empty_policy() {
// Content of less than 32 bytes.
let small_content = b"some text content";
let small_uri = mxc_uri!("mxc://server.local/small");
let small_request = MediaRequestParameters {
source: MediaSource::Plain(small_uri.to_owned()),
format: MediaFormat::File,
};
// Content of more than 32 bytes.
let big_content = b"some much much larger text content";
let big_uri = mxc_uri!("mxc://server.local/big");
let big_request = MediaRequestParameters {
source: MediaSource::Plain(big_uri.to_owned()),
format: MediaFormat::File,
};
// Limit the file size to 32 bytes in the retention policy.
let policy = MediaRetentionPolicy { max_file_size: Some(32), ..Default::default() };
let now = SystemTime::UNIX_EPOCH;
let store = MockEventCacheStoreMedia::default();
let service = MediaService::with_time_provider(MockTimeProvider::new(now));
// Check that restoring the policy works.
service.restore(Some(MediaRetentionPolicy::default()), None);
assert_eq!(service.media_retention_policy(), MediaRetentionPolicy::default());
assert!(!store.accessed());
// Set the media retention policy.
service.set_media_retention_policy(&store, policy).await.unwrap();
assert!(store.accessed());
assert_eq!(service.media_retention_policy(), policy);
assert_eq!(store.inner().media_retention_policy, Some(policy));
store.reset_accessed();
// Add small media, it should work because its size is lower than the max file
// size.
service
.add_media_content(
&store,
&small_request,
small_content.to_vec(),
IgnoreMediaRetentionPolicy::No,
)
.await
.unwrap();
assert!(store.accessed());
let media_content = store.inner().media_list[0].clone();
assert_eq!(media_content.uri, small_uri);
assert_eq!(media_content.content, small_content);
assert!(!media_content.ignore_policy);
assert_eq!(media_content.last_access, now);
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
store.reset_accessed();
// Get media from request.
let loaded_content = service.get_media_content(&store, &small_request).await.unwrap();
assert!(store.accessed());
assert_eq!(loaded_content.as_deref(), Some(small_content.as_slice()));
// The last access time was updated.
let media = store.inner().media_list[0].clone();
assert_eq!(media.last_access, now);
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
store.reset_accessed();
// Get media from URI.
let loaded_content = service.get_media_content_for_uri(&store, small_uri).await.unwrap();
assert!(store.accessed());
assert_eq!(loaded_content.as_deref(), Some(small_content.as_slice()));
// The last access time was updated.
let media = store.inner().media_list[0].clone();
assert_eq!(media.last_access, now);
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
store.reset_accessed();
// Add big media, it will not work because it is bigger than the max file size.
service
.add_media_content(
&store,
&big_request,
big_content.to_vec(),
IgnoreMediaRetentionPolicy::No,
)
.await
.unwrap();
assert!(!store.accessed());
assert_eq!(store.inner().media_list.len(), 1);
store.reset_accessed();
let loaded_content = service.get_media_content(&store, &big_request).await.unwrap();
assert!(store.accessed());
assert_eq!(loaded_content, None);
store.reset_accessed();
let loaded_content = service.get_media_content_for_uri(&store, big_uri).await.unwrap();
assert!(store.accessed());
assert_eq!(loaded_content, None);
// Add big media, but this time ignore the policy.
service
.add_media_content(
&store,
&big_request,
big_content.to_vec(),
IgnoreMediaRetentionPolicy::Yes,
)
.await
.unwrap();
assert!(store.accessed());
assert_eq!(store.inner().media_list.len(), 2);
store.reset_accessed();
// Get media from request.
let loaded_content = service.get_media_content(&store, &big_request).await.unwrap();
assert!(store.accessed());
assert_eq!(loaded_content.as_deref(), Some(big_content.as_slice()));
// The last access time was updated.
let media = store.inner().media_list[1].clone();
assert_eq!(media.last_access, now);
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
store.reset_accessed();
// Get media from URI.
let loaded_content = service.get_media_content_for_uri(&store, big_uri).await.unwrap();
assert!(store.accessed());
assert_eq!(loaded_content.as_deref(), Some(big_content.as_slice()));
// The last access time was updated.
let media = store.inner().media_list[1].clone();
assert_eq!(media.last_access, now);
// Try a cleanup, the store should be accessed.
assert_eq!(store.last_media_cleanup_time_inner().await.unwrap(), None);
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
store.reset_accessed();
service.clean_up_media_cache(&store).await.unwrap();
assert!(store.accessed());
assert_eq!(store.last_media_cleanup_time_inner().await.unwrap(), Some(now));
}
#[async_test]
async fn test_media_service_automatic_cleanup() {
// 64 bytes content.
let content = vec![0; 64];
let uri_1 = mxc_uri!("mxc://localhost/media-1");
let request_1 = MediaRequestParameters {
source: MediaSource::Plain(uri_1.to_owned()),
format: MediaFormat::File,
};
let uri_2 = mxc_uri!("mxc://localhost/media-2");
let request_2 = MediaRequestParameters {
source: MediaSource::Plain(uri_2.to_owned()),
format: MediaFormat::File,
};
let now = SystemTime::UNIX_EPOCH;
let store = MockEventCacheStoreMedia::default();
let service = MediaService::with_time_provider(MockTimeProvider::new(now));
// Set an empty policy.
let policy = MediaRetentionPolicy::empty();
service.set_media_retention_policy(&store, policy).await.unwrap();
// Add the contents.
service
.add_media_content(&store, &request_1, content.clone(), IgnoreMediaRetentionPolicy::No)
.await
.unwrap();
service
.add_media_content(&store, &request_2, content, IgnoreMediaRetentionPolicy::No)
.await
.unwrap();
assert!(service.inner.automatic_media_cleanup_join_handle.lock().is_none());
// Try to launch an automatic cleanup.
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
service.maybe_spawn_automatic_media_cache_cleanup(&store, now);
// No cleanup was spawned since automatic cleanups are disabled.
assert!(service.inner.automatic_media_cleanup_join_handle.lock().is_none());
// Set a policy with automatic cleanup every hour.
let policy = MediaRetentionPolicy::empty()
.with_cleanup_frequency(Some(Duration::from_secs(60 * 60)));
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
service.set_media_retention_policy(&store, policy).await.unwrap();
// No cleanup was spawned since the policy has no limitations.
assert!(service.inner.automatic_media_cleanup_join_handle.lock().is_none());
// Set a policy with automatic cleanup every hour and a max file size.
let policy = MediaRetentionPolicy::empty()
.with_cleanup_frequency(Some(Duration::from_secs(60 * 60)))
.with_max_file_size(Some(512));
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
service.set_media_retention_policy(&store, policy).await.unwrap();
// A cleanup was spawned since there was no last_media_cleanup_time.
let join_handle = service.inner.automatic_media_cleanup_join_handle.lock().take().unwrap();
join_handle.await.unwrap();
assert_eq!(store.last_media_cleanup_time_inner().await.unwrap(), Some(now));
// Try again one minute in the future, nothing is spawned because we need to
// wait for one hour.
let now = now + Duration::from_secs(60);
service.inner.time_provider.set_now(now);
service.get_media_content(&store, &request_1).await.unwrap();
assert!(service.inner.automatic_media_cleanup_join_handle.lock().is_none());
// Try again 2 hours in the future, another cleanup is spawned.
let now = now + Duration::from_secs(2 * 60 * 60);
service.inner.time_provider.set_now(now);
service.get_media_content_for_uri(&store, uri_1).await.unwrap();
let join_handle = service.inner.automatic_media_cleanup_join_handle.lock().take().unwrap();
join_handle.await.unwrap();
assert_eq!(store.last_media_cleanup_time_inner().await.unwrap(), Some(now));
}
}