1
use super::DBError;
2
use std::sync::OnceLock;
3

            
4
/// The admin database URL: set explicitly once, otherwise read from
5
/// `DATABASE_URL` on first use. The first resolution is final.
6
pub(super) struct UrlSource {
7
    resolved: OnceLock<Option<String>>,
8
}
9

            
10
impl UrlSource {
11
5
    pub(super) const fn new() -> Self {
12
5
        Self {
13
5
            resolved: OnceLock::new(),
14
5
        }
15
5
    }
16

            
17
364
    pub(super) fn set(&self, url: String) -> Result<(), DBError> {
18
364
        self.resolved
19
364
            .set(Some(url))
20
            .map_err(|_| DBError::UrlAlreadyResolved)
21
364
    }
22

            
23
396365
    pub(super) fn get_or_env(&self, env: impl FnOnce() -> Option<String>) -> Option<&str> {
24
396365
        self.resolved.get_or_init(env).as_deref()
25
396365
    }
26
}
27

            
28
static DB_URL: UrlSource = UrlSource::new();
29

            
30
55080
fn env_url() -> Option<String> {
31
55080
    std::env::var("DATABASE_URL").ok()
32
55080
}
33

            
34
/// Makes `url` the admin database URL instead of `DATABASE_URL`.
35
///
36
/// # Errors
37
/// [`DBError::UrlAlreadyResolved`] if a URL was already set or any code
38
/// already resolved the URL from the environment.
39
360
pub fn use_url(url: String) -> Result<(), DBError> {
40
360
    DB_URL.set(url)
41
360
}
42

            
43
/// The admin database URL the server was configured with.
44
///
45
/// # Errors
46
/// [`DBError::MissingUrl`] if no URL was set and `DATABASE_URL` is unset.
47
118800
pub fn admin_database_url() -> Result<String, DBError> {
48
118800
    current_url().map(str::to_owned).ok_or(DBError::MissingUrl)
49
118800
}
50

            
51
396360
pub(super) fn current_url() -> Option<&'static str> {
52
396360
    DB_URL.get_or_env(env_url)
53
396360
}
54

            
55
#[cfg(test)]
56
mod tests {
57
    use super::*;
58

            
59
3
    fn env(url: &'static str) -> impl FnOnce() -> Option<String> {
60
2
        move || Some(url.to_owned())
61
3
    }
62

            
63
    #[test]
64
1
    fn explicit_url_wins_over_env() {
65
1
        let source = UrlSource::new();
66
1
        assert!(source.set("postgres://explicit/db".into()).is_ok());
67
1
        assert_eq!(
68
1
            source.get_or_env(env("postgres://env/db")),
69
1
            Some("postgres://explicit/db")
70
        );
71
1
    }
72

            
73
    #[test]
74
1
    fn env_is_used_when_nothing_was_set() {
75
1
        let source = UrlSource::new();
76
1
        assert_eq!(
77
1
            source.get_or_env(env("postgres://env/db")),
78
1
            Some("postgres://env/db")
79
        );
80
1
    }
81

            
82
    #[test]
83
1
    fn missing_everywhere_resolves_to_none() {
84
1
        let source = UrlSource::new();
85
1
        assert_eq!(source.get_or_env(|| None), None);
86
1
    }
87

            
88
    #[test]
89
1
    fn second_set_is_refused() {
90
1
        let source = UrlSource::new();
91
1
        assert!(source.set("postgres://a/db".into()).is_ok());
92
1
        assert!(matches!(
93
1
            source.set("postgres://b/db".into()),
94
            Err(DBError::UrlAlreadyResolved)
95
        ));
96
1
        assert_eq!(source.get_or_env(|| None), Some("postgres://a/db"));
97
1
    }
98

            
99
    #[test]
100
1
    fn set_after_first_use_is_refused() {
101
1
        let source = UrlSource::new();
102
1
        assert_eq!(
103
1
            source.get_or_env(env("postgres://env/db")),
104
1
            Some("postgres://env/db")
105
        );
106
1
        assert!(matches!(
107
1
            source.set("postgres://late/db".into()),
108
            Err(DBError::UrlAlreadyResolved)
109
        ));
110
1
    }
111
}