1
use crate::db::{DBError, get_connection};
2
use derive_more::From;
3
use rust_i18n::t;
4
use sqlx::Error::RowNotFound;
5
use std::env::var;
6
use std::fmt;
7
use std::sync::LazyLock;
8
use thiserror::Error;
9

            
10
/// Represents an error that can occur while accessing the configuration.
11
///
12
/// # Variants
13
///
14
/// - `NoConfig(String)`: Returned when a specific configuration field is not found.
15
/// - `Sqlx`: An error propagated from the `SQLx` crate.
16
///
17
/// # Example
18
///
19
/// ```rust
20
/// use thiserror::Error;
21
///
22
/// #[derive(Debug, Error)]
23
/// pub enum ConfigError {
24
///     #[error("No such config field: {0}")]
25
///     NoConfig(String),
26
///     #[error("Sqlx")]
27
///     Sqlx(#[from] sqlx::Error),
28
/// }
29
/// ```
30
#[derive(Debug, Error)]
31
pub enum ConfigError {
32
    #[error("No such config field: {0}")]
33
    NoConfig(String),
34
    #[error("Email must not be empty")]
35
    EmailBlank,
36
    #[error("Email is already registered")]
37
    EmailTaken,
38
    #[error("{0}")]
39
    InvalidTimezone(String),
40
    // The underlying error is carried through: swallowing it turned a unique
41
    // violation into the word "Sqlx" in the log, which names no cause at all.
42
    #[error("{0}")]
43
    Sqlx(#[from] sqlx::Error),
44
}
45

            
46
/// Represents a configuration value stored in the system.
47
///
48
/// # Variants
49
///
50
/// - `String`: Stores the configuration as a string.
51
/// - `Blob`: Stores the configuration as a binary blob.
52
///
53
/// # Example
54
///
55
/// ```rust
56
/// use server::config::ConfigOption;
57
/// let config_str = ConfigOption::String("example".to_string());
58
/// let config_blob = ConfigOption::Blob(vec![1, 2, 3, 4]);
59
/// ```
60
///
61
/// You can also convert `String` and `Vec<u8>` directly into `ConfigOption`
62
/// using the `From` trait:
63
///
64
/// ```rust
65
/// use server::config::ConfigOption;
66
/// let config: ConfigOption = "example".to_string().into();
67
/// let blob: ConfigOption = vec![1, 2, 3, 4].into();
68
/// ```
69
#[derive(Debug, From, PartialEq, Clone)]
70
pub enum ConfigOption {
71
    String(#[from] String),
72
    Blob(#[from] Vec<u8>),
73
}
74

            
75
impl fmt::Display for ConfigOption {
76
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77
        match self {
78
            ConfigOption::String(s) => write!(f, "{s}"),
79
            ConfigOption::Blob(b) => write!(f, "ConfigOption<Blob>: \"{}\" bytes", b.len()),
80
        }
81
    }
82
}
83

            
84
/// Allows for the conversion from a `&str` to `ConfigOption`.
85
///
86
/// This is useful for passing string literals or string slices directly as `ConfigOption`.
87
/// The conversion will wrap the `&str` in the `ConfigOption::String` variant.
88
///
89
/// # Example
90
///
91
/// ```rust
92
/// use server::config::ConfigOption;
93
/// let config_option: ConfigOption = "example text".into();
94
/// assert_eq!(config_option, ConfigOption::String("example text".to_string()));
95
/// ```
96
impl From<&str> for ConfigOption {
97
    fn from(value: &str) -> Self {
98
        ConfigOption::String(value.to_string())
99
    }
100
}
101

            
102
/// Convert `ConfigOption` into a `&[u8]` reference when the variant is a `Blob`.
103
///
104
/// # Example
105
///
106
/// ```rust
107
/// use server::config::ConfigOption;
108
/// let config = ConfigOption::Blob(vec![1, 2, 3]);
109
/// let byte_ref: &[u8] = config.as_ref(); // Works
110
/// ```
111
impl AsRef<[u8]> for ConfigOption {
112
    fn as_ref(&self) -> &[u8] {
113
        match self {
114
            ConfigOption::String(s) => s.as_bytes(),
115
            ConfigOption::Blob(b) => b.as_slice(),
116
        }
117
    }
118
}
119

            
120
// The config read/write logic is identical for the system (admin DB) and
121
// per-user surfaces — only the connection differs. The `*_on` helpers take an
122
// explicit connection so both surfaces share one implementation; `User::config`
123
// / `User::set_config` (see `user.rs`) pass a per-user connection, while the
124
// `system_*` wrappers below pass the global admin connection.
125

            
126
/// Fetches the `contents` of a field from the configdata.
127
///
128
/// This function attempts to retrieve the configuration stored in the
129
/// `configdata` table.  If the field is not found, it returns a
130
/// `ConfigError::NoConfig`.
131
///
132
/// # Arguments
133
///
134
/// - `field`: The name of the field to retrieve.
135
///
136
/// # Returns
137
///
138
/// - `Ok(Some(ConfigOption))` if the field exists.
139
/// - `Err(ConfigError::NoConfig)` if the field is absent from both the
140
///   `config` and `configdata` tables (callers that treat "absent" as
141
///   "not set" — e.g. the `GetConfig` command — normalise this to `Ok(None)`).
142
/// - `Err(ConfigError)` on any other retrieval error.
143
///
144
/// # Example
145
///
146
/// ```rust,ignore
147
/// let config = system_configdata("example_field").await?;
148
/// if let Some(option) = config {
149
///     println!("Config value: {}", option);
150
/// }
151
/// ```
152
///
153
/// # Errors
154
///
155
/// Returns a `ConfigError::Sqlx` if the query fails.
156
134103
async fn configdata_on(
157
134103
    conn: &mut sqlx::PgConnection,
158
134103
    field: &str,
159
134103
) -> Result<Option<ConfigOption>, ConfigError> {
160
134103
    let value = sqlx::query_file_scalar!("../server/sql/select/config/data.sql", field)
161
134103
        .fetch_one(&mut *conn)
162
134103
        .await
163
134102
        .map_err(|err| match err {
164
134102
            RowNotFound => ConfigError::NoConfig(String::from(field)),
165
            err => ConfigError::Sqlx(err),
166
134102
        })?;
167

            
168
1
    Ok(Some(ConfigOption::Blob(value)))
169
134103
}
170

            
171
/// Reads a config field on the given connection: the `config` (string) table
172
/// first, falling back to `configdata` (blob).
173
///
174
/// # Errors
175
/// `ConfigError::Sqlx` on a database error.
176
143468
pub async fn config_on(
177
143468
    conn: &mut sqlx::PgConnection,
178
143468
    field: &str,
179
143468
) -> Result<Option<ConfigOption>, ConfigError> {
180
143468
    let value = sqlx::query_file_scalar!("../server/sql/select/config/string.sql", field)
181
143468
        .fetch_one(&mut *conn)
182
143468
        .await;
183
143468
    match value {
184
9365
        Ok(l) => Ok(Some(ConfigOption::String(l))),
185
134103
        Err(RowNotFound) => configdata_on(conn, field).await,
186
        Err(err) => Err(ConfigError::Sqlx(err)),
187
    }
188
143468
}
189

            
190
/// Upserts a config field on the given connection (string → `config`, blob →
191
/// `configdata`). The upsert keys on `lower(field)` (see the SQL), so it is
192
/// idempotent and case-insensitive.
193
///
194
/// # Errors
195
/// `ConfigError::Sqlx` on a database error, `ConfigError::NoConfig` if the row is
196
/// missing for an update.
197
7208
pub async fn set_config_on(
198
7208
    conn: &mut sqlx::PgConnection,
199
7208
    field: &str,
200
7208
    contents: ConfigOption,
201
7208
) -> Result<(), ConfigError> {
202
7208
    let id = uuid::Uuid::new_v4();
203
7208
    match contents {
204
        ConfigOption::String(s) => {
205
7207
            sqlx::query_file!("../server/sql/set/config/string.sql", &id, field, s)
206
        }
207
        ConfigOption::Blob(b) => {
208
1
            sqlx::query_file!("../server/sql/set/config/blob.sql", &id, field, b)
209
        }
210
    }
211
7208
    .execute(&mut *conn)
212
7208
    .await
213
    .map_err(|err| match err {
214
        RowNotFound => ConfigError::NoConfig(String::from(field)),
215
        err => ConfigError::Sqlx(err),
216
    })?;
217

            
218
7208
    Ok(())
219
7208
}
220

            
221
/// Every string config field on the given connection, ordered by name.
222
///
223
/// # Errors
224
/// `ConfigError::Sqlx` on a database error.
225
1261
pub async fn list_config_on(
226
1261
    conn: &mut sqlx::PgConnection,
227
1261
) -> Result<Vec<(String, String)>, ConfigError> {
228
1261
    let rows = sqlx::query_file!("../server/sql/select/config/list.sql")
229
1261
        .fetch_all(&mut *conn)
230
1261
        .await?;
231
1442
    Ok(rows.into_iter().map(|r| (r.field, r.contents)).collect())
232
1261
}
233

            
234
/// Reads a SYSTEM (server-wide) config field from the global admin database.
235
/// For server-wide keys (infra URLs, locale) and the bootstrap reads that run
236
/// before any user is resolved. Per-user config goes through `User::config`.
237
///
238
/// # Errors
239
/// [`DBError`] when the directory is unreachable or the query fails.
240
51842
pub async fn system_config(field: &str) -> Result<Option<ConfigOption>, DBError> {
241
51842
    let mut conn = get_connection().await?;
242
51662
    Ok(config_on(&mut conn, field).await?)
243
51662
}
244

            
245
/// Reads a SYSTEM config blob field from the global admin database.
246
///
247
/// # Errors
248
/// [`DBError`] when the directory is unreachable or the query fails.
249
pub async fn system_configdata(field: &str) -> Result<Option<ConfigOption>, DBError> {
250
    let mut conn = get_connection().await?;
251
    Ok(configdata_on(&mut conn, field).await?)
252
}
253

            
254
/// Writes a SYSTEM config field to the global admin database.
255
///
256
/// # Errors
257
/// [`DBError`] when the directory is unreachable or the query fails.
258
2
pub async fn set_system_config(field: &str, contents: ConfigOption) -> Result<(), DBError> {
259
2
    let mut conn = get_connection().await?;
260
2
    Ok(set_config_on(&mut conn, field, contents).await?)
261
2
}
262

            
263
180
static LOCALE_NAME: LazyLock<String> = LazyLock::new(|| var("LANG").unwrap_or(String::from("en")));
264

            
265
180
pub async fn load_config() -> Result<(), ConfigError> {
266
    // Matched rather than deref'd: only the String variant names a locale, and
267
    // a Blob in that row should fall back rather than panic the boot.
268
180
    if let Ok(Some(ConfigOption::String(locale))) = system_config("locale").await {
269
        rust_i18n::set_locale(&locale);
270
        tracing::info!(
271
            "{}",
272
            t!(
273
                "Loaded the %{loc} locale from config, setting as main",
274
                loc = &locale
275
            )
276
        );
277
    } else {
278
180
        rust_i18n::set_locale(&LOCALE_NAME);
279
    }
280
180
    Ok(())
281
180
}
282

            
283
#[cfg(test)]
284
mod config_tests {
285
    use super::*;
286
    use crate::db::install_test_pool;
287
    use sqlx::PgPool;
288
    use supp_macro::local_db_sqlx_test;
289
    use tokio::sync::OnceCell;
290

            
291
    /// Context for keeping environment intact
292
    static CONTEXT: OnceCell<()> = OnceCell::const_new();
293

            
294
2
    async fn setup() {
295
2
        CONTEXT
296
2
            .get_or_init(|| async {
297
2
                crate::telemetry::init_test_logging();
298
4
            })
299
2
            .await;
300
2
    }
301

            
302
    #[local_db_sqlx_test]
303
    async fn test_config_string(pool: PgPool) {
304
        let opt = ConfigOption::String("testval".to_string());
305
        set_system_config("testfield", opt.clone()).await.unwrap();
306
        let val = system_config("testfield").await.unwrap().unwrap();
307
        assert_eq!(val, opt);
308
    }
309

            
310
    #[local_db_sqlx_test]
311
    async fn test_config_configdata(pool: PgPool) {
312
        let opt = ConfigOption::Blob(vec![0, 1, 2, 3]);
313
        set_system_config("testblob", opt.clone()).await.unwrap();
314
        let val = system_config("testblob").await.unwrap().unwrap();
315
        assert_eq!(val, opt);
316
    }
317
}