forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

settings.rs256 lines, 8.4 KiBHistoryRawDownload
1//! Runtime settings: the operator's values that change without a restart, and where each one comes from.
2//!
3//! The precedence is fixed: a UI override (a row of the `settings` table, written by the admin page), then
4//! the file (`[limits]` in the configuration), then the built-in default. [`resolve`] returns the value
5//! together with the layer it came from, so the admin page can show the source beside each value. Every
6//! caller reads through [`resolve`], so the rule is written once. Nothing here changes the database.
7
8use crate::config::Limits;
9use crate::error::{Error, Result};
10use crate::quota::DEFAULT_MEMBER_QUOTA;
11use crate::store::Store;
12use crate::store::objects::DEFAULT_SERVICE_QUOTA;
13
14/// Settings key of the quota a new person gets, in bytes.
15pub const DEFAULT_QUOTA_KEY: &str = "default_quota_bytes";
16/// Settings key of the quota a new service namespace gets, in bytes.
17pub const DEFAULT_SERVICE_QUOTA_KEY: &str = "default_service_quota_bytes";
18/// Settings key of the days trash waits before a purge.
19pub const PURGE_KEY: &str = "purge_after_days";
20/// Settings key of the largest upload, in bytes.
21pub const MAX_UPLOAD_KEY: &str = "max_upload_bytes";
22/// Settings key of the longest share link, in days.
23pub const LINK_MAX_DAYS_KEY: &str = "link_max_days";
24
25/// One GiB in bytes.
26const GIB: i64 = 1024 * 1024 * 1024;
27/// One MiB in bytes.
28const MIB: i64 = 1024 * 1024;
29/// One TiB in bytes: the upper bound of every byte value, far above any real quota.
30const TIB: i64 = 1024 * GIB;
31
32/// Default purge delay: 30 days.
33pub const DEFAULT_PURGE_AFTER_DAYS: i64 = 30;
34/// Default largest upload: 50 GiB.
35pub const DEFAULT_MAX_UPLOAD: i64 = 50 * GIB;
36/// Default longest share link: a year.
37pub const DEFAULT_LINK_MAX_DAYS: i64 = 365;
38
39/// How a field may change. Shown on the admin page next to the value.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum Mode {
42 /// The next request that reads the value uses the new one.
43 Live,
44 /// Takes effect after a restart of the process.
45 Restart,
46 /// Set in the file only, and shown but not editable.
47 ReadOnly,
48}
49
50/// The layer a value came from.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum Source {
53 /// Set on the admin page.
54 Ui,
55 /// Set in the configuration file.
56 File,
57 /// The built-in default.
58 Default,
59}
60
61/// A value and the layer it came from.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct Resolved {
64 /// The value in the field's unit.
65 pub value: i64,
66 /// Which layer supplied it.
67 pub source: Source,
68}
69
70/// One field the admin page can show or change: its key, default, the bounds a value must meet, and its
71/// mode. Byte fields are in bytes and day fields in days.
72#[derive(Debug)]
73pub struct Field {
74 /// The settings key, also the key in the file's `[limits]` table.
75 pub key: &'static str,
76 /// The built-in default.
77 pub default: i64,
78 /// Smallest value accepted.
79 pub min: i64,
80 /// Largest value accepted.
81 pub max: i64,
82 /// How the value may change.
83 pub mode: Mode,
84}
85
86/// Every field of the admin page's defaults section, in display order.
87pub const FIELDS: [Field; 5] = [
88 Field {
89 key: DEFAULT_QUOTA_KEY,
90 default: DEFAULT_MEMBER_QUOTA,
91 min: 0,
92 max: TIB,
93 mode: Mode::Live,
94 },
95 Field {
96 key: DEFAULT_SERVICE_QUOTA_KEY,
97 default: DEFAULT_SERVICE_QUOTA,
98 min: 0,
99 max: TIB,
100 mode: Mode::Live,
101 },
102 Field {
103 key: PURGE_KEY,
104 default: DEFAULT_PURGE_AFTER_DAYS,
105 min: 1,
106 max: 3650,
107 mode: Mode::Live,
108 },
109 Field {
110 key: MAX_UPLOAD_KEY,
111 default: DEFAULT_MAX_UPLOAD,
112 min: MIB,
113 max: TIB,
114 mode: Mode::Live,
115 },
116 Field {
117 key: LINK_MAX_DAYS_KEY,
118 default: DEFAULT_LINK_MAX_DAYS,
119 min: 1,
120 max: 3650,
121 mode: Mode::Live,
122 },
123];
124
125/// The field with this key, if it is one of [`FIELDS`].
126pub fn field(key: &str) -> Option<&'static Field> {
127 FIELDS.iter().find(|field| field.key == key)
128}
129
130/// The file value of `key`, when the `[limits]` table sets it.
131pub fn file_value(limits: &Limits, key: &str) -> Option<i64> {
132 match key {
133 DEFAULT_QUOTA_KEY => limits.default_quota_bytes,
134 DEFAULT_SERVICE_QUOTA_KEY => limits.default_service_quota_bytes,
135 PURGE_KEY => limits.purge_after_days,
136 MAX_UPLOAD_KEY => limits.max_upload_bytes,
137 LINK_MAX_DAYS_KEY => limits.link_max_days,
138 _ => None,
139 }
140}
141
142/// Checks a value against the field's bounds. The refusal word is the key with `_range`, which the
143/// admin page turns into a sentence.
144pub fn check(field: &Field, value: i64) -> Result<i64> {
145 if value < field.min || value > field.max {
146 return Err(Error::Invalid(format!("{}_range", field.key)));
147 }
148 Ok(value)
149}
150
151/// Parses the text of an admin form for `key`. Blank means "no override": `Ok(None)`. Anything else
152/// must be an integer within the field's bounds.
153pub fn parse_ui(key: &str, text: &str) -> Result<Option<i64>> {
154 let field = field(key).ok_or_else(|| Error::Invalid("unknown_setting".into()))?;
155 let text = text.trim();
156 if text.is_empty() {
157 return Ok(None);
158 }
159 let value: i64 = text
160 .parse()
161 .map_err(|_| Error::Invalid(format!("{}_range", field.key)))?;
162 check(field, value).map(Some)
163}
164
165/// Checks every value the file sets. Called by `Config::validate`, so a bad file fails at boot.
166pub fn check_file(limits: &Limits) -> Result<()> {
167 for field in &FIELDS {
168 if let Some(value) = file_value(limits, field.key) {
169 check(field, value).map_err(|_| {
170 Error::Config(format!(
171 "limits.{} must be between {} and {}",
172 field.key, field.min, field.max
173 ))
174 })?;
175 }
176 }
177 Ok(())
178}
179
180/// The effective value of `key`: the UI override when one is stored and valid, else the file value, else
181/// the default. A stored override that is out of bounds (possible only by hand-editing the database) is
182/// ignored and the next layer is used.
183pub async fn resolve(store: &Store, limits: &Limits, key: &str) -> Result<Resolved> {
184 let field = field(key).ok_or_else(|| Error::Invalid("unknown_setting".into()))?;
185 if let Some(text) = store.get_setting(key).await?
186 && let Some(value) = text
187 .trim()
188 .parse::<i64>()
189 .ok()
190 .filter(|v| check(field, *v).is_ok())
191 {
192 return Ok(Resolved {
193 value,
194 source: Source::Ui,
195 });
196 }
197 if let Some(value) = file_value(limits, key) {
198 return Ok(Resolved {
199 value,
200 source: Source::File,
201 });
202 }
203 Ok(Resolved {
204 value: field.default,
205 source: Source::Default,
206 })
207}
208
209/// The word the admin page shows for a source: `ui`, `file` or `default`. The page translates it.
210pub fn source_word(source: Source) -> &'static str {
211 match source {
212 Source::Ui => "ui",
213 Source::File => "file",
214 Source::Default => "default",
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221 use crate::store::Store;
222
223 #[test]
224 fn blank_clears_and_bounds_are_enforced() {
225 assert_eq!(parse_ui(PURGE_KEY, " ").unwrap(), None);
226 assert_eq!(parse_ui(PURGE_KEY, "30").unwrap(), Some(30));
227 assert!(parse_ui(PURGE_KEY, "0").is_err());
228 assert!(parse_ui(PURGE_KEY, "3651").is_err());
229 assert!(parse_ui(PURGE_KEY, "soon").is_err());
230 assert!(parse_ui("nope", "1").is_err());
231 }
232
233 #[tokio::test]
234 async fn ui_beats_file_beats_default() {
235 let dir = tempfile::tempdir().unwrap();
236 let store = Store::open(&dir.path().join("in.db")).await.unwrap();
237 let limits = Limits {
238 purge_after_days: Some(7),
239 ..Limits::default()
240 };
241 let from_file = resolve(&store, &limits, PURGE_KEY).await.unwrap();
242 assert_eq!(from_file.value, 7);
243 assert_eq!(from_file.source, Source::File);
244
245 store.set_setting(PURGE_KEY, "14").await.unwrap();
246 let from_ui = resolve(&store, &limits, PURGE_KEY).await.unwrap();
247 assert_eq!(from_ui.value, 14);
248 assert_eq!(from_ui.source, Source::Ui);
249
250 let default = resolve(&store, &Limits::default(), LINK_MAX_DAYS_KEY)
251 .await
252 .unwrap();
253 assert_eq!(default.value, DEFAULT_LINK_MAX_DAYS);
254 assert_eq!(default.source, Source::Default);
255 }
256}