Skip to main content

tuwunel_service/media/
space.rs

1use std::{path::Path, sync::Arc};
2
3use http::StatusCode;
4use ruma::api::error::{ErrorKind, ResourceLimitExceededErrorData};
5use tuwunel_core::{
6	Error, Result, config::StorageProvider, defer, extract_variant, implement,
7	smallvec::SmallVec, utils::sys::storage::available_space, warn,
8};
9
10use crate::storage::Provider;
11
12// an upload is nearly always written to one provider
13type Providers = SmallVec<[Arc<Provider>; 1]>;
14
15/// Refuse an upload while storage it would be written to is short of space.
16///
17/// Each local storage provider an upload is written to is asked for the space
18/// available on its filesystem, and the upload is refused while any of them
19/// has less than `media.upload_min_free_space`. A provider that is not a
20/// directory has no such figure, and one that cannot be read refuses nothing.
21#[implement(super::Service)]
22#[tracing::instrument(level = "debug", skip_all)]
23pub async fn check_upload_space(&self) -> Result {
24	let min_free_space = self.services.config.media.upload_min_free_space;
25
26	if min_free_space == 0 {
27		return Ok(());
28	}
29
30	let providers: Providers = self
31		.upload_providers()
32		.filter(|provider| matches!(provider.config, StorageProvider::local(_)))
33		.cloned()
34		.collect();
35
36	if providers.is_empty() {
37		return Ok(());
38	}
39
40	let task = self
41		.services
42		.server
43		.runtime()
44		.spawn_blocking(move || any_short_of_space(&providers, min_free_space));
45
46	// on cancellation, drop a read still queued for the blocking pool
47	let abort = task.abort_handle();
48
49	defer! {{ abort.abort(); }}
50
51	if !task.await? {
52		return Ok(());
53	}
54
55	Err(Error::Request(
56		// the spec requires admin_contact; clients use support discovery
57		ErrorKind::ResourceLimitExceeded(ResourceLimitExceededErrorData::new(String::new())),
58		"The server is short of storage space and is not accepting uploads.".into(),
59		StatusCode::FORBIDDEN,
60	))
61}
62
63/// Whether any local provider's filesystem is short of space.
64///
65/// The first one found is logged with the space it has left. A filesystem that
66/// cannot be read is passed over with a warning, so a check that never runs is
67/// visible.
68fn any_short_of_space<'a, I>(providers: I, min_free_space: u64) -> bool
69where
70	I: IntoIterator<Item = &'a Arc<Provider>>,
71{
72	providers
73		.into_iter()
74		.filter_map(|provider| extract_variant!(&provider.config, StorageProvider::local))
75		.any(|local| {
76			let path = &local.base_path;
77
78			available_space(Path::new(path))
79				.inspect_err(|error| {
80					warn!(%path, %error, "Cannot read the space left for uploads.");
81				})
82				.ok()
83				.filter(|&available| is_short_of_space(available, min_free_space))
84				.inspect(|available| {
85					warn!(
86						%path, available, min_free_space,
87						"Refusing uploads while storage is short of space."
88					);
89				})
90				.is_some()
91		})
92}
93
94/// Whether this much available space refuses an upload.
95///
96/// Space exactly at the minimum is enough, so only less than it refuses.
97#[inline]
98#[must_use]
99pub(super) fn is_short_of_space(available: u64, min_free_space: u64) -> bool {
100	available < min_free_space
101}